分享 node 面试题
发布于 7 年前 作者 XiomgMingCai 4734 次浏览 来自 分享

这题 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 面试题 传送门

6 回复

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

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 拥有块级作用域,就不用你那样别扭的写法了

@fantasticsoul 第二部分的console.log(new Date(), i);,i 呢?而且块级作用域是 es6 规范。我看了半天没想到面试官想考什么。

回到顶部