javascript:尝试通过async / await和IIFE获得同步行为

问题描述 投票:-1回答:1

在下面的代码中,我想依次获取msg#1,msg#2,msg#3。我现在正在:味精1,味精3,味精2。感谢帮助 !拒绝

function timeoutPromise(time) { return new Promise(function (resolve) { setTimeout(function () { resolve(Date.now()); }, time) }) }
function wait(howlong) { return timeoutPromise(howlong * 1000); }
async function doAsync() {
  var start = Date.now(), time;
  time = await wait(1); console.log('... ' + (time-start)/1000 );
  time = await wait(1); console.log('... ' + (time-start)/1000 );
}
console.log('msg#1');
(async () => { await doAsync(); console.log('msg#2'); })();
console.log('msg#3');
asynchronous async-await iife
1个回答
0
投票

[async函数是异步的!

倒数第二行的功能将到达await doAsync();,进入睡眠状态,父功能将在下一行console.log('msg#3');处继续。

如果要等待异步功能完成,也需要将其await

© www.soinside.com 2019 - 2024. All rights reserved.