下面代码怎么分别使用Promise和async改写成每隔1s打印1个数字的形式?

分别使用Promise和async改写成每隔1s打印1个数字的形式

function print(n){
    for(var i = 0;i <n;i++){
        setTimeout(console.log, 1000, i);
    }
}
print(10);
阅读 1.7k
2 个回答

async/await:

const sleep = t => new Promise(res => setTimeout(res, t))
const print = async n => {
    for (let i = 0; i < n; i ++) {
        console.log(i)
        await sleep(1000)
    }
}

纯 Promise(有必要吗?)

const print = n => Array(n).fill().reduce((p, _, i) => p.then(() => new Promise(res => {
    console.log(i)
    setTimeout(res, 1000)
}, Promise.resolve())

也不用 Promise

const print = (n, i = 0) => {
    if (i === n) return
    console.log(i)
    setTimeout(() => print(n, i + 1), 1000)
}

改造 setTimeout

const asyncSetTimeout = (timeout = 1e3, ...params) => {
  let timer = 0;
  let rejectRef = null;
  const result = new Promise((resolve, reject) => {
    rejectRef = reject;
    timer = setTimeout(() => {
      resolve(params);
    }, timeout);
  });
  result.cancelTimeout = (reason) => {
    clearTimeout(timer);
    rejectRef(reason);
  };
  return result
};

Promise 版本

const print = (times, curTime = 0) => {
  asyncSetTimeout().then(() => {
    console.log(curTime);
    times && print(times - 1, curTime + 1);
  })
}

async-await 版本

const print = async (times, curTime = 0) => {
  await asyncSetTimeout(1e3);
  console.log(curTime);
  times && print(times - 1, curTime + 1);
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏