那么如何使异步呢?

时间:2018-07-09 03:23:33

标签: javascript promise async-await

基本上,我想尝试了解async/await中更多的promiseJS。我正在尝试使你好介于完成!第三名之间!。因此,最好的猜测是,使第二个then成为asnyc并等待console.log('Hello')。我在下面尝试了两种方法,但都无法按预期工作。

方法A

let promise = new Promise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(() => {
  setTimeout(async function(){     
    await console.log("Hello"); }, 3000); //async/await at setTimeout level
}).then(() => {
  console.log('third finish!!')
})

方法B:

let promise = new Promise((res,rej)=>{
      res();
    });

    promise.then(() => {
      console.log('finished!')
    }).then(async () => { //async/await at thenlevel
      await setTimeout(function(){     
        console.log("Hello"); }, 3000); 
    }).then(() => {
      console.log('third finish!!')
    })

2 个答案:

答案 0 :(得分:2)

您需要将第二部分设置为Promise,并从.then返回它,以便在第一部分和第三部分之间正确链接。 setTimeout不返回Promise,您必须显式构造一个Promise

let promise = new Promise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(() => {
  return new Promise(resolve => {
    setTimeout(function(){     
      console.log("Hello");
      resolve();
    }, 1000);
  });
}).then(() => {
  console.log('third finish!!')
})

或者,使用await,使用await new Promise,然后使用相同的Promise构造和setTimeout

let promise = new Promise((res, rej) => {
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(async() => {
  await new Promise(resolve => {
    setTimeout(function() {
      console.log("Hello");
      resolve();
    }, 1000);
  });
}).then(() => {
  console.log('third finish!!')
})

答案 1 :(得分:0)

另一种方法是编写一个异步setAsyncTimeout函数(尚未经过全面测试,可能需要进行调整):

async function setAsyncTimeout(callback, interval) {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            try {
                let inner = callback()
                if (inner && inner.then) {
                    inner.then(resolve, reject)
                } else {
                    resolve(inner)
                }
            } catch(e) {
                reject(e)
            }
        }, interval)
    })
}

通过您的示例进行测试:

let promise = new Promise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then( setAsyncTimeout(function(){     
    console.log("Hello"); }, 3000); 
}).then(() => {
  console.log('third finish!!')
})

通过您的示例进行测试(带有另一个承诺):

let promise = new Promise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(async () => { //async/await at thenlevel
  await setAsyncTimeout(function(){     
    console.log("Hello");
    return setAsyncTimeout(() => console.log("world"), 3000)
  }, 3000); 
}).then(() => {
  console.log('third finish!!')
})

更干净的示例:

let promise = new Promise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(() => {
  return setAsyncTimeout(() => { console.log("Hello"); }, 3000)
}).then(() => {
  console.log('third finish!!')
})