| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/for-await...of | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 ..
for await...of , , , : String, Array, Array- (., arguments NodeList), TypedArray, Map, Set, / . , .
for await (variable of iterable) {
statement
}
, .
var asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve({ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
},
};
},
};
(async function () {
for await (let num of asyncIterable) {
console.log(num);
}
})();
// 0
// 1
// 2
Iterator, for await... of
async function* asyncGenerator() {
var i = 0;
while (i < 3) {
yield i++;
}
}
(async function () {
for await (let num of asyncGenerator()) {
console.log(num);
}
})();
// 0
// 1
// 2
for await... of, API. , API.
async function* streamAsyncIterator(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
return;
}
yield value;
}
} finally {
reader.releaseLock();
}
}
// Fetches data from url and calculates response size using the async generator.
async function getResponseSize(url) {
const response = await fetch(url);
// Will hold the size of the response, in bytes.
let responseSize = 0;
// The for-await-of loop. Async iterates over each portion of the response.
for await (const chunk of streamAsyncIterator(response.body)) {
// Incrementing the total response length.
responseSize += chunk.length;
}
console.log(`Response Size: ${responseSize} bytes`);
// expected output: "Response Size: 1071472"
return responseSize;
}
getResponseSize("https://jsonplaceholder.typicode.com/photos");
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-for-in-and-for-of-statements |
This page was last modified on 6 . 2024 . by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |