Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with awaiting a promise chain?

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);
});

I realize that it is pointless to await a promise chain. If someFunction() returns a promise, you don’t need a promise chain if you’re awaiting it. You can do this:

const result = await someFunction();
console.log(result);

But I’m being told awaiting a promise chain can cause bugs, or that it will break things in my code. If the first code snippet above does the same thing as the second snippet, what does it matter which one is used. What dangers does the first snippet introduce that the second one doesn’t?

like image 980
Gibran Shah Avatar asked Jan 27 '19 06:01

Gibran Shah


Video Answer


1 Answers

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.

like image 122
dwjohnston Avatar answered Oct 12 '22 11:10

dwjohnston