What's wrong with awaiting a promise chain?

前端 未结 3 2059
借酒劲吻你
借酒劲吻你 2020-11-22 15:43

I’m working on an Angular 6 application and I’ve been told the following is an anti-pattern:

await someFunction().then(result => {
    console.log(result)         


        
3条回答
  •  眼角桃花
    2020-11-22 16:08

    Under the hood, async/await is just promises.

    That is, when you have some code that looks like:

    const result = await myAsyncFunction();   
    console.log(result): 
    

    That's exactly the same as writing:

    myAsyncFunction().then(data => {
       const result = data; 
       console.log(result); 
    }); 
    

    The reason then - that you shouldn't mix async/await and .then chains - is because it's confusing.

    It's better to just pick one style, and stick to it.

    And while you're picking one - you might as well pick async/await - it's more understandable.

提交回复
热议问题