should we choose async await over Promise in Javascript

后端 未结 3 1837
小蘑菇
小蘑菇 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:30

    Your benchmark has nothing to do with the performance between async/await vs raw promises. All I can see is that throwing an error takes a longer time to compute. This is expected.

    Back to the main question, should use async/await rather than .then with raw promises?

    Keep in mind that async/await is merely syntactic sugar over raw promises, so there shouldn't be much impact on the overall performance. However, it does make your code more linear which removes a lot of cognitive overhead from the developer.

    The conclusion is use what you prefer. Promises can be polyfill'd but new syntaxes cannot, so you might want to keep that in mind when deciding which style to use.


    Some misunderstanding:

    The error stack returned from a promise chain gives no clue of where the error happened

    That is not true. A quick check with:

    function error() {
        return new Promise(function(res, rej) {
            res(undefined()); // uh oh
        });
    }
    
    error().then(console.log, e => console.log("Uh oh!", e.stack));

    shows the entire error stack including the location.

提交回复
热议问题