Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async / await vs then which is the best for performance?

I have a simple code in JavaScript that execute a request in an API and return the response, simple. But in this case I will have thousands of requests. So, which one of the code options will perform better, and why. Also which one is recommended as good pratices these days?

First options is using the .then to resolve the promises and the seccond one is using async / await.

In my tests the two options had very similar results without significant differences, but I'm not sure in scale.

// Using then doSomething(payload) {   const url = 'https://link-here/consultas';   return this.axios.get(url, {     params: {       token: payload.token,       chave: payload.chave,     },    }).then(resp => resp.data); }  // Using Async / await async doSomething(payload) {    const url = 'https://link-here/consultas';    const resp = await this.axios.get(url, {    params: {      token: payload.token,      chave: payload.chave,     },  });  return resp.data; } 

Any explanation will be of great value.

like image 849
Francisco Avatar asked Feb 02 '19 17:02

Francisco


People also ask

Which is better async await or then?

Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then() , the rest of the function will continue to execute but JavaScript won't execute the . then() callback until the promise settles.

Does async await improve performance?

The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.

Should we use then with async await?

The await keyword is used to get a value from a function where you would normally use . then() . Instead of calling . then() after the asynchronous function, you would simply assign a variable to the result using await .

Why are async await better than promise then design pattern?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.


2 Answers

await is just an internal version of .then() (doing basically the same thing). The reason to choose one over the other doesn't really have to do with performance, but has to do with desired coding style or coding convenience. Certainly, the interpreter has a few more opportunities to optimize things internally with await, but its unlikely that should be how you decide which to use. If all else was equal, I would choose await for the reason cited above. But, I'd first choose which made the code simpler to write and understand and maintain and test.

Used properly, await can often save you a bunch of lines of code making your code simpler to read, test and maintain. That's why it was invented.

There's no meaningful difference between the two versions of your code. Both achieve the same result when the axios call is successful or has an error.

Where await could make more of a convenience difference is if you had multiple successive asynchronous calls that needed to be serialized. Then, rather than bracketing them each inside a .then() handler to chain them properly, you could just use await and have simpler looking code.

A common mistake with both await and .then() is to forget proper error handling. If your error handling desire in this function is to just return the rejected promise, then both of your versions do that identically. But, if you have multiple async calls in a row and you want to do anything more complex than just returning the first rejection, then the error handling techniques for await and .then()/.catch() are quite different and which seems simpler will depend upon the situation.

like image 130
jfriend00 Avatar answered Oct 18 '22 18:10

jfriend00


There should be some corrections in this thread. await and .then are going to give very different results, and should be used for different reasons.

await will WAIT for something, and then continue to the next line. It's also the simpler of the two because it behaves mechanically more like synchronous behavior. You do step #1, wait, and then continue.

console.log("Runs first."); await SomeFunction(); console.log("Runs last."); 

.then splits off from the original call and starts operating within its own scope, and will update at a time the original scope cannot predict. If we can put semantics aside for a moment, it's "more asynchronous," because it leaves the old scope and branches off into a new one.

console.log("Runs first."); SomeFunction().then((value) => {console.log("Runs last (probably). Didn't use await on SomeFunction().")}) console.log("Runs second (probably)."); 
like image 20
user280209 Avatar answered Oct 18 '22 18:10

user280209