JavaScript await by default instead of manually

前端 未结 1 530
时光取名叫无心
时光取名叫无心 2021-01-14 04:57

Async/await are really handy, but I want the opposite of their behavior. Instead of other functions continuing on unless I manually ask them to await a promise, I want funct

相关标签:
1条回答
  • 2021-01-14 05:54

    Implicit await is bad, for reasons covered well in this blog. In short, consider why there's no need for locking in JavaScript. It's because we don't worry about being pre-empted willy-nilly.

    Also, as mentioned by Daniel in comments, global await is not allowed either, presumably for backwards compatibility.

    You can work around this by wrapping your top-level code like this:

    let wait = ms => new Promise(r => setTimeout(r, ms));
    
    async function a() {
      console.log("1");
      await wait(5000);
      console.log("2");
    }
    
    (async () => {
    
      // Put your top level code here!
    
      await a();
      console.log("3");
    
    })().catch(e => setTimeout(() => { throw e; }));

    Not perfect, but gets the job done, without turning everything upside down.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题