As its name suggests, the await keyword will cause the function to βwaitβ for its promise to resolve before executing the next line. The whole point of await is to make the code wait for the operation to complete before continuing.
The difference between this and the blocking code is that the world outside the function can continue to execute while the function is waiting for the completion of asynchronous operations.
async and await are just syntactic sugar in addition to promises. They allow you to write code that is very similar to regular synchronous code, even if it uses promises undercover. If we translated your example into something that obviously worked with promises, it would look something like this:
function myAsyncFunction() { return myAPICall('https://jsonplaceholder.typicode.com/posts/1') .then(function (data) { let result = 2 + 2; return data; }) .catch(function (ex) { return ex; }); }
As we can see here, the string let result = 2 + 2; is inside the .then() handler, which means that it will not be executed until myAPICall() resolved. Same thing when you use await . await just abstracts .then() for you.
Keep in mind (and I think you're looking) that you do not need to use await immediately. If you wrote your function this way, you could immediately execute the string let result = 2 + 2; :
After some clarification, I see that you really wanted to learn how to avoid having to wait for two asynchronous operations one after another and instead execute them in parallel. Indeed, if you use one await after another, the second will not start executing until the first ends:
To avoid this, you can run both asynchronous operations by doing them, not expecting them, assigning their promises to some variables. Then you can wait for both promises:
An alternative way to do this is to use Promise.all() with some decomposition of the array:
Jlrishe
source share