【问题标题】:javascript : trying to get a synchronous behaviour with async/await and IIFEjavascript:尝试使用 async/await 和 IIFE 获得同步行为
【发布时间】:2019-12-07 09:40:38
【问题描述】:

在下面的代码中,我想按此顺序获取 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】:

    async 函数是异步的!

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

    如果你想等待那个异步函数完成,你也需要await它。

    【讨论】:

    • 感谢昆汀,这不是我想要用 IIFE 做的吗:(async () => { await doAsync(); console.log('msg#2'); } )(); ?
    • 你有一个await IIFE,但不在它之外。
    • 对不起,我对 JS async/await 的无知,您介意提供可以完成这项工作的确切行吗?非常感谢。
    • 那么终于有一个简单实用的方法来回答这个问题了吗?
    【解决方案2】:

    我会建议自己的答案,更多的是解决方法而不是真正的答案.. 让我们希望我们能从社区中得到更好的答案。

    (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 味精#3

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多