Asynchronous javascript:尝试使用async/await和IIFE获得同步行为

Asynchronous javascript:尝试使用async/await和IIFE获得同步行为,asynchronous,async-await,iife,Asynchronous,Async Await,Iife,在下面的代码中,我希望按以下顺序获得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(howl

在下面的代码中,我希望按以下顺序获得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');

async
函数是异步的

倒数第二行的函数将到达
wait doAsync()
,进入睡眠状态,父函数将继续执行下一行
console.log('msg#3')


如果您想等待异步函数完成,您也需要等待它。

我会建议自己的答案,与其说是真正的答案,不如说是一种变通方法。。 希望我们能从社区得到更好的答案

(async () => { await doAsync(); console.log('msg#2'); everythingThatFollowsdoAsync(); })();

    function everythingThatFollowsdoAsync(){
        // let's do here the rest of the code, now that doAsync() is over. 
        console.log('msg#3');   
 }
然后我得到了预期的输出:

味精#1 1.002 2.003 味精#2
msg#3

谢谢昆汀,这不正是我试图对IIFE所做的:(async()=>{await doAsync();console.log('msg#2');})()?在iLife中有一个
await
,但在iLife之外没有。很抱歉我不知道JS async/await,您介意提供完成此任务的确切行吗?非常感谢。那么最后有没有一个简单实用的方法来回答这个问题呢?