那么如何使异步呢? [英] How to make an async then?

查看:57
本文介绍了那么如何使异步呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically I am trying to play around to understand more of async/await and promise in JS. I'm trying to make Hello comes in between finished! and third finish!!. So the best guess is, making second then asnyc and await for console.log('Hello'). I've tried both ways below but both are not working as expected.

方法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!!')
    })

推荐答案

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

You need the second section to be a Promise, and return it from the .then so that it's properly chained between the first and the third. setTimeout doesn't return a Promise, you have to explicitly construct a Promise instead:

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:

Or, using await, use await new Promise followed by the same Promise construction and the 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!!')
})

这篇关于那么如何使异步呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆