should we choose async await over Promise in Javascript

后端 未结 3 1809
小蘑菇
小蘑菇 2021-01-17 16:45

I know that the async await is the new Promise in the town and it is a new way to write asynchronous code and I also know that

We didn’t ha

3条回答
  •  无人及你
    2021-01-17 17:16

    Building on unional's answer:

    You can achieve the same behavior as Promise.all with async/await

    function foo() {
      Promise.all([backend.doSomething(), backend.doAnotherThing()])
        .then(([a, b]) => {
           return a + b
        })
    }
    
    async function foo() {
      const a = backend.doSomething()
      const b = backend.doAnotherThing()
      return await a + await b
    }
    

    Backend tasks happen concurrently and we wait on both to be finished before we return. See also the MDN example I wrote

    Based on this I am not sure if there is any performance advantage to directly using Promises over async/await.

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