重构承诺异步/等待。为什么我没有受到伤害?

时间:2018-04-15 07:22:17

标签: javascript promise async-await

我在Promise上有代码:

function one() {
  return new Promise((rs,er)=>{
  console.log('start');
  new Promise((rr,err)=>{setTimeout(()=>{console.log('after 3 sec');rr()},3000)})
    .then( sd => {
      console.log('endLong');
      rs();
      })
    });
}

one().then(_ => one()).then(_ => one());

结果我获得了同步代码。

但是当我将它重构为async / wait

async function one() {
  console.log('start');
  await longtime();
  console.log('endLong');
}

async function longtime() {setTimeout(()=>{console.log('after 3 sec');},3000);}

one().then(_ => one()).then(_ => one())
然后我得到了:

start
endLong
start
endLong
start
endLong
Promise {<resolved>: undefined}
after 3 sec
after 3 sec
after 3 sec

怎么了?

2 个答案:

答案 0 :(得分:1)

您需要A#getStuff()才能返回承诺。单独使用longtime并不意味着基于承诺setTimeout / async

await

答案 1 :(得分:0)

setTimeout不会返回承诺。异步函数应该返回一个使用值解析的promise。

 function longtime() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('after 3 sec');
      resolve();
    }, 3000);
  });