分享 node 面试题
发布于 24 天前 作者 XiomgMingCai 548 次浏览 来自 分享

这题 es7 解法!

let sleep = [];

for (var i = 0; i < 5; i++) {
    ((j) => {
        sleep.push(new Promise(function (resolve, reject) {

            setTimeout(function () {
                console.log(new Date, j);
                resolve();
            }, j * 1000)
        }))
    })(i)
}
 // await只能使用在原生语法
(async () => {
    for (let item of sleep) {
        await item
    }
    console.log(new Date(), i);
})();

北京 某个公司Node.js 面试题 传送门

5 回复

你这样写感觉有点奇怪, 不知我这样写怎么样?

let sleep = [];

for (var i = 0; i < 5; i++) {
    ((j) => {
        sleep.push(new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log(new Date, j);
                resolve();
            }, j * 1000)
        }))
    })(i)
}
(async () => {
    await Promise.all(sleep);
    console.log(new Date(), i);
})();

那样写的话输出是0->1->2->3->4,5吧

0->1->2->3->4->5的话

const sleep = (time, i) => new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(new Date, i);
    resolve();
  },time);
});

(async () => {
  let i = 0;
  for (; i < 5; i++) {
    await sleep(1000, i);
  }
  setTimeout(() => {
    console.log(new Date, i);
  }, 1000);
})();

都es7,你这个写法还是不够精简 let sleep = []; for (let i = 0; i < 5; i++) { sleep.push(new Promise(function (resolve, reject) { setTimeout(()=> { console.log(new Date, j); resolve();}, j * 1000) })) } (async () => { await Promise.all(sleep); console.log(new Date(), i); })();

let 拥有块级作用域,就不用你那样别扭的写法了

回到顶部