关于node.js:for-await-…of-表达式的煎蛋实现小demo

38次阅读

共计 584 个字符,预计需要花费 2 分钟才能阅读完成。

偶然间看到一个小例子:

import {serve} from "https://deno.land/std@0.69.0/http/server.ts";
 const s = serve({port: 8000});
 console.log("http://localhost:8000/");
 for await (const req of s) {req.respond({ body: "Hello Worldn"});
 }

查了查资料有了上面这个小 demo:

const simulateDelay = (val, delay) =>
    new Promise((resolve) => setTimeout(() => resolve(val), delay));
class RandomNumberGenerator {[Symbol.asyncIterator]() {
        return {next: async () => {return simulateDelay({ value: Math.random() }, 200); //return the value after 200ms of delay
 },
 };
 }
}
const rand = new RandomNumberGenerator();
(async () => {for await (const random of rand) {console.log(random);
 if (random < 0.1) break;
 }
})();

正文完
 0