【问题标题】:JavaScript: Using await to make asnyc code look more synchronous [duplicate]JavaScript:使用 await 使 asnyc 代码看起来更同步 [重复]
【发布时间】:2020-10-05 09:23:57
【问题描述】:

我正在尝试了解 asnyc 等待功能。 因此,我想使用一个 asnyc 函数,解决它并执行以下日志随后

我如何实现这一目标?还是我理解的根本错误?

const test = async function() {
    console.log('hi 1');
    await setTimeout(() => {
        console.log('timout1')
    }, 1000);
    console.log('hi 2');
    console.log('hi 3');
}
test()

结果

hi 1
hi 2
hi 3
timout1

预期结果

hi 1
timout1
hi 2
hi 3

【问题讨论】:

    标签: javascript asynchronous


    【解决方案1】:

    我希望这段代码能帮助你理解异步等待。

    function resolveAfter2Seconds() {
      	return new Promise(resolve => {
        	setTimeout(() => {
          		resolve('resolved');
        	}, 2000);
      	});
    }
    
    async function asyncCall() {
      	console.log('hi 1');
      	const result = await resolveAfter2Seconds();
      	console.log(result);
      	console.log('hi 2');
      	console.log('hi 3');
    }
    
    asyncCall();

    【讨论】:

      【解决方案2】:

      您只能将await 用于promise,而setTimeout 函数不会返回Promise。但是,您可以等待使用 setTimeout 解决的 Promise,这样会给您想要的结果。

      因此,函数执行将停止,直到被 awaited 的 Promise 解决或被拒绝,然后继续。

      const test = async function() {
        console.log('hi 1');
               // return a new promise resolved after setTimeout callback is fired
        await (new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log('timout1')
            resolve()
          }, 1000)
        }))
        console.log('hi 2');
        console.log('hi 3');
      }
      
      test()

      希望这会有所帮助!

      【讨论】:

      • 啊!你说的对!仅仅因为 setTimeout() 是 asnyc 并不意味着它是一个承诺!
      猜你喜欢
      • 2019-10-12
      • 2014-11-18
      • 2014-09-28
      • 2018-12-31
      • 1970-01-01
      • 2013-01-28
      • 2017-05-07
      • 2020-06-27
      相关资源
      最近更新 更多