乐趣区

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

偶然间看到一个小例子:

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;
 }
})();
退出移动版