Why doesn't the code after await run right away? Isn't it supposed to be non-blocking?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







10















Hi guys i have a hard time understanding how async and await works behind the scenes. I know we have promises which make our non blocking code by using the "then" function we can place all the work we need to do after the promise is resolved. and the work we want to do parallel to promise we just write it outside our then function. Hence the code becomes non blocking. However i don't understand how the async await makes non-blocking code.



async function myAsyncFunction() {
try {
let data = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// It will not run this line until it resolves await.
let result = 2 + 2;
return data;
}catch (ex){
return ex;
}
}


See the above code. I cannot move forward until the API call is resolved. If it makes my code blocking code, how is it any better then promises? Or is there something I missed about async and await? Where do i put my code that is not dependent to the await call? so it can keep on working without await holding the execution?



I am adding a Promise code that i would like to replicate in an async await example.



function myPromiseAPI() {
myAPICall('https://jsonplaceholder.typicode.com/posts/1')
.then(function (data) {
// data
});
// runs parallel
let result = 2 + 2;
}









share|improve this question

























  • AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

    – Paul
    Apr 9 '17 at 3:01











  • It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

    – nnnnnn
    Apr 9 '17 at 3:06













  • @Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

    – Rohail Najam
    Apr 9 '17 at 3:07











  • @nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

    – Rohail Najam
    Apr 9 '17 at 3:09











  • @RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

    – Paul
    Apr 9 '17 at 3:12


















10















Hi guys i have a hard time understanding how async and await works behind the scenes. I know we have promises which make our non blocking code by using the "then" function we can place all the work we need to do after the promise is resolved. and the work we want to do parallel to promise we just write it outside our then function. Hence the code becomes non blocking. However i don't understand how the async await makes non-blocking code.



async function myAsyncFunction() {
try {
let data = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// It will not run this line until it resolves await.
let result = 2 + 2;
return data;
}catch (ex){
return ex;
}
}


See the above code. I cannot move forward until the API call is resolved. If it makes my code blocking code, how is it any better then promises? Or is there something I missed about async and await? Where do i put my code that is not dependent to the await call? so it can keep on working without await holding the execution?



I am adding a Promise code that i would like to replicate in an async await example.



function myPromiseAPI() {
myAPICall('https://jsonplaceholder.typicode.com/posts/1')
.then(function (data) {
// data
});
// runs parallel
let result = 2 + 2;
}









share|improve this question

























  • AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

    – Paul
    Apr 9 '17 at 3:01











  • It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

    – nnnnnn
    Apr 9 '17 at 3:06













  • @Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

    – Rohail Najam
    Apr 9 '17 at 3:07











  • @nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

    – Rohail Najam
    Apr 9 '17 at 3:09











  • @RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

    – Paul
    Apr 9 '17 at 3:12














10












10








10


6






Hi guys i have a hard time understanding how async and await works behind the scenes. I know we have promises which make our non blocking code by using the "then" function we can place all the work we need to do after the promise is resolved. and the work we want to do parallel to promise we just write it outside our then function. Hence the code becomes non blocking. However i don't understand how the async await makes non-blocking code.



async function myAsyncFunction() {
try {
let data = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// It will not run this line until it resolves await.
let result = 2 + 2;
return data;
}catch (ex){
return ex;
}
}


See the above code. I cannot move forward until the API call is resolved. If it makes my code blocking code, how is it any better then promises? Or is there something I missed about async and await? Where do i put my code that is not dependent to the await call? so it can keep on working without await holding the execution?



I am adding a Promise code that i would like to replicate in an async await example.



function myPromiseAPI() {
myAPICall('https://jsonplaceholder.typicode.com/posts/1')
.then(function (data) {
// data
});
// runs parallel
let result = 2 + 2;
}









share|improve this question
















Hi guys i have a hard time understanding how async and await works behind the scenes. I know we have promises which make our non blocking code by using the "then" function we can place all the work we need to do after the promise is resolved. and the work we want to do parallel to promise we just write it outside our then function. Hence the code becomes non blocking. However i don't understand how the async await makes non-blocking code.



async function myAsyncFunction() {
try {
let data = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// It will not run this line until it resolves await.
let result = 2 + 2;
return data;
}catch (ex){
return ex;
}
}


See the above code. I cannot move forward until the API call is resolved. If it makes my code blocking code, how is it any better then promises? Or is there something I missed about async and await? Where do i put my code that is not dependent to the await call? so it can keep on working without await holding the execution?



I am adding a Promise code that i would like to replicate in an async await example.



function myPromiseAPI() {
myAPICall('https://jsonplaceholder.typicode.com/posts/1')
.then(function (data) {
// data
});
// runs parallel
let result = 2 + 2;
}






javascript async-await es6-promise ecmascript-2017






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 3 '17 at 15:31









JLRishe

77.4k1180119




77.4k1180119










asked Apr 9 '17 at 2:58









Rohail NajamRohail Najam

421410




421410













  • AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

    – Paul
    Apr 9 '17 at 3:01











  • It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

    – nnnnnn
    Apr 9 '17 at 3:06













  • @Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

    – Rohail Najam
    Apr 9 '17 at 3:07











  • @nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

    – Rohail Najam
    Apr 9 '17 at 3:09











  • @RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

    – Paul
    Apr 9 '17 at 3:12



















  • AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

    – Paul
    Apr 9 '17 at 3:01











  • It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

    – nnnnnn
    Apr 9 '17 at 3:06













  • @Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

    – Rohail Najam
    Apr 9 '17 at 3:07











  • @nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

    – Rohail Najam
    Apr 9 '17 at 3:09











  • @RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

    – Paul
    Apr 9 '17 at 3:12

















AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

– Paul
Apr 9 '17 at 3:01





AFAIK, await requires that the thing it's awaiting be a promise. So it's not really a either/or.

– Paul
Apr 9 '17 at 3:01













It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

– nnnnnn
Apr 9 '17 at 3:06







It's sort of as if the lines after your "until it resolves" comment are inside a .then(). And your whole function is itself async, so whatever calls it doesn't have to wait for it.

– nnnnnn
Apr 9 '17 at 3:06















@Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

– Rohail Najam
Apr 9 '17 at 3:07





@Paul it also converts the expression in promise if it is not a promise. that what i read in a blog

– Rohail Najam
Apr 9 '17 at 3:07













@nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

– Rohail Najam
Apr 9 '17 at 3:09





@nnnnnn Yes. its like i put that in .then(). but how do i put it outside a then() in async await scenario

– Rohail Najam
Apr 9 '17 at 3:09













@RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

– Paul
Apr 9 '17 at 3:12





@RohailNajam Right, my point was about async calls, though. Using a function that expects a callback in place of that promise would not work.

– Paul
Apr 9 '17 at 3:12












1 Answer
1






active

oldest

votes


















25














Just as its name implies, the await keyword will cause the function to "wait" until its promise resolves before executing the next line.



The difference between this and blocking code is that the world outside the function will continue to go on executing while the function is waiting for the asynchronous operations to finish.



async and await are just syntactic sugar on top of promises. They allow you to write code that looks a lot like ordinary synchronous code even though it uses promises under the covers. If we translated your example there to something that explicitly worked with the promises, it would look something like:



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 let result = 2 + 2; line is inside a .then() handler, which means it's not going to execute until myAPICall() has resolved. It's the same when you use await. await just abstracts away the .then() for you.



One thing to bear in mind (and I think the point you're looking for) is that you don't have to use await right away. If you wrote your function like this, then you could execute your let result = 2 + 2; line right away:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





After some clarification, I can see that what you really wanted to know about is how to avoid having to wait for two async operations one by one and instead have them execute in parallel. Indeed, if you use one await after the other, the second won't start executing until the first has finished:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





To avoid this, what you can do is start both async operations by executing them without awaiting them, assigning their promises to some variables. Then you can await both promises:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





One alternative way to do this is to use Promise.all() with some array decomposition:






function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();








share|improve this answer


























  • I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

    – Rohail Najam
    Apr 9 '17 at 3:20











  • @RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

    – JLRishe
    Apr 9 '17 at 3:25













  • oh i did not knew that. Thanks.

    – Rohail Najam
    Apr 9 '17 at 3:27






  • 2





    @RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

    – JLRishe
    Apr 9 '17 at 11:37






  • 1





    "the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

    – a better oliver
    Apr 12 '17 at 8:14












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43302584%2fwhy-doesnt-the-code-after-await-run-right-away-isnt-it-supposed-to-be-non-blo%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









25














Just as its name implies, the await keyword will cause the function to "wait" until its promise resolves before executing the next line.



The difference between this and blocking code is that the world outside the function will continue to go on executing while the function is waiting for the asynchronous operations to finish.



async and await are just syntactic sugar on top of promises. They allow you to write code that looks a lot like ordinary synchronous code even though it uses promises under the covers. If we translated your example there to something that explicitly worked with the promises, it would look something like:



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 let result = 2 + 2; line is inside a .then() handler, which means it's not going to execute until myAPICall() has resolved. It's the same when you use await. await just abstracts away the .then() for you.



One thing to bear in mind (and I think the point you're looking for) is that you don't have to use await right away. If you wrote your function like this, then you could execute your let result = 2 + 2; line right away:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





After some clarification, I can see that what you really wanted to know about is how to avoid having to wait for two async operations one by one and instead have them execute in parallel. Indeed, if you use one await after the other, the second won't start executing until the first has finished:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





To avoid this, what you can do is start both async operations by executing them without awaiting them, assigning their promises to some variables. Then you can await both promises:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





One alternative way to do this is to use Promise.all() with some array decomposition:






function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();








share|improve this answer


























  • I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

    – Rohail Najam
    Apr 9 '17 at 3:20











  • @RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

    – JLRishe
    Apr 9 '17 at 3:25













  • oh i did not knew that. Thanks.

    – Rohail Najam
    Apr 9 '17 at 3:27






  • 2





    @RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

    – JLRishe
    Apr 9 '17 at 11:37






  • 1





    "the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

    – a better oliver
    Apr 12 '17 at 8:14
















25














Just as its name implies, the await keyword will cause the function to "wait" until its promise resolves before executing the next line.



The difference between this and blocking code is that the world outside the function will continue to go on executing while the function is waiting for the asynchronous operations to finish.



async and await are just syntactic sugar on top of promises. They allow you to write code that looks a lot like ordinary synchronous code even though it uses promises under the covers. If we translated your example there to something that explicitly worked with the promises, it would look something like:



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 let result = 2 + 2; line is inside a .then() handler, which means it's not going to execute until myAPICall() has resolved. It's the same when you use await. await just abstracts away the .then() for you.



One thing to bear in mind (and I think the point you're looking for) is that you don't have to use await right away. If you wrote your function like this, then you could execute your let result = 2 + 2; line right away:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





After some clarification, I can see that what you really wanted to know about is how to avoid having to wait for two async operations one by one and instead have them execute in parallel. Indeed, if you use one await after the other, the second won't start executing until the first has finished:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





To avoid this, what you can do is start both async operations by executing them without awaiting them, assigning their promises to some variables. Then you can await both promises:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





One alternative way to do this is to use Promise.all() with some array decomposition:






function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();








share|improve this answer


























  • I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

    – Rohail Najam
    Apr 9 '17 at 3:20











  • @RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

    – JLRishe
    Apr 9 '17 at 3:25













  • oh i did not knew that. Thanks.

    – Rohail Najam
    Apr 9 '17 at 3:27






  • 2





    @RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

    – JLRishe
    Apr 9 '17 at 11:37






  • 1





    "the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

    – a better oliver
    Apr 12 '17 at 8:14














25












25








25







Just as its name implies, the await keyword will cause the function to "wait" until its promise resolves before executing the next line.



The difference between this and blocking code is that the world outside the function will continue to go on executing while the function is waiting for the asynchronous operations to finish.



async and await are just syntactic sugar on top of promises. They allow you to write code that looks a lot like ordinary synchronous code even though it uses promises under the covers. If we translated your example there to something that explicitly worked with the promises, it would look something like:



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 let result = 2 + 2; line is inside a .then() handler, which means it's not going to execute until myAPICall() has resolved. It's the same when you use await. await just abstracts away the .then() for you.



One thing to bear in mind (and I think the point you're looking for) is that you don't have to use await right away. If you wrote your function like this, then you could execute your let result = 2 + 2; line right away:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





After some clarification, I can see that what you really wanted to know about is how to avoid having to wait for two async operations one by one and instead have them execute in parallel. Indeed, if you use one await after the other, the second won't start executing until the first has finished:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





To avoid this, what you can do is start both async operations by executing them without awaiting them, assigning their promises to some variables. Then you can await both promises:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





One alternative way to do this is to use Promise.all() with some array decomposition:






function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();








share|improve this answer















Just as its name implies, the await keyword will cause the function to "wait" until its promise resolves before executing the next line.



The difference between this and blocking code is that the world outside the function will continue to go on executing while the function is waiting for the asynchronous operations to finish.



async and await are just syntactic sugar on top of promises. They allow you to write code that looks a lot like ordinary synchronous code even though it uses promises under the covers. If we translated your example there to something that explicitly worked with the promises, it would look something like:



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 let result = 2 + 2; line is inside a .then() handler, which means it's not going to execute until myAPICall() has resolved. It's the same when you use await. await just abstracts away the .then() for you.



One thing to bear in mind (and I think the point you're looking for) is that you don't have to use await right away. If you wrote your function like this, then you could execute your let result = 2 + 2; line right away:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





After some clarification, I can see that what you really wanted to know about is how to avoid having to wait for two async operations one by one and instead have them execute in parallel. Indeed, if you use one await after the other, the second won't start executing until the first has finished:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





To avoid this, what you can do is start both async operations by executing them without awaiting them, assigning their promises to some variables. Then you can await both promises:






function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





One alternative way to do this is to use Promise.all() with some array decomposition:






function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();








function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// just starting the API call and storing the promise for now. not waiting yet
let dataP = myAPICall('https://jsonplaceholder.typicode.com/posts/1');

let result = 2 + 2;

// Executes right away
console.log(result);

let data = await dataP;

// Executes after one second
console.log(data);

return data;
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

let data1 = await myAPICall('https://jsonplaceholder.typicode.com/posts/1');
// logs after one second
console.log(data1);

let data2 = await myAPICall('https://jsonplaceholder.typicode.com/posts/2');
// logs after one more second
console.log(data1);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');
// both lines execute right away
let dataP1 = myAPICall('https://jsonplaceholder.typicode.com/posts/1');
let dataP2 = myAPICall('https://jsonplaceholder.typicode.com/posts/2');

let data1 = await dataP1;
let data2 = await dataP2;

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();





function myAPICall() {
// simulate 1 second wait time
console.log('myAPICall called');
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => 'success');
}

async function myAsyncFunction() {
try {
console.log('starting');

// both myAPICall invocations execute right away
const [data1, data2] = await Promise.all([
myAPICall('https://jsonplaceholder.typicode.com/posts/1'),
myAPICall('https://jsonplaceholder.typicode.com/posts/2'),
]);

// logs after one second
console.log(data1);
console.log(data2);
} catch (ex) {
return ex;
}
}

myAsyncFunction();






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 3 at 15:53

























answered Apr 9 '17 at 3:15









JLRisheJLRishe

77.4k1180119




77.4k1180119













  • I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

    – Rohail Najam
    Apr 9 '17 at 3:20











  • @RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

    – JLRishe
    Apr 9 '17 at 3:25













  • oh i did not knew that. Thanks.

    – Rohail Najam
    Apr 9 '17 at 3:27






  • 2





    @RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

    – JLRishe
    Apr 9 '17 at 11:37






  • 1





    "the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

    – a better oliver
    Apr 12 '17 at 8:14



















  • I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

    – Rohail Najam
    Apr 9 '17 at 3:20











  • @RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

    – JLRishe
    Apr 9 '17 at 3:25













  • oh i did not knew that. Thanks.

    – Rohail Najam
    Apr 9 '17 at 3:27






  • 2





    @RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

    – JLRishe
    Apr 9 '17 at 11:37






  • 1





    "the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

    – a better oliver
    Apr 12 '17 at 8:14

















I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

– Rohail Najam
Apr 9 '17 at 3:20





I understand this. what my point is that if we want to run anything in parallel to this api call we will just put it next to the then function like i did in my edited question. How will i achieve this "Parallelism" in async await

– Rohail Najam
Apr 9 '17 at 3:20













@RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

– JLRishe
Apr 9 '17 at 3:25







@RohailNajam Please see my update. You can "start" as many promises in parallel as you want. Once you use await, the function will start waiting on their result.

– JLRishe
Apr 9 '17 at 3:25















oh i did not knew that. Thanks.

– Rohail Najam
Apr 9 '17 at 3:27





oh i did not knew that. Thanks.

– Rohail Najam
Apr 9 '17 at 3:27




2




2





@RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

– JLRishe
Apr 9 '17 at 11:37





@RohailNajam Yes, that's correct. I've modified my answer to show how you can use array decomposition to split it into its respective values.

– JLRishe
Apr 9 '17 at 11:37




1




1





"the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

– a better oliver
Apr 12 '17 at 8:14





"the world outside the function will continue to go on executing while this function is doing its thing" The "world outside" will go on while the function is not doing anything.

– a better oliver
Apr 12 '17 at 8:14




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43302584%2fwhy-doesnt-the-code-after-await-run-right-away-isnt-it-supposed-to-be-non-blo%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

MongoDB - Not Authorized To Execute Command

in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

How to fix TextFormField cause rebuild widget in Flutter