Async function without await in JavascriptUsing async without awaitJavascript: await function endend before loop continueHow do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?var functionName = function() vs function functionName() Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
Why are stats in Angband written as 18/** instead of 19, 20...?
Why does the U.S military use mercenaries?
Is it a good idea to teach algorithm courses using pseudocode instead of a real programming language?
How do you cope with rejection?
Should all adjustments be random effects in a mixed linear effect?
Alternative classical explanation of the Stern-Gerlach Experiment?
Hotel booking: Why is Agoda much cheaper than booking.com?
Gambler's Fallacy Dice
Taylor series leads to two different functions - why?
Why are there five extra turns in tournament Magic?
Cycling to work - 30mile return
How to laser-level close to a surface
How to say "that" as in "the cow that ate" in Japanese?
Why does a table with a defined constant in its index compute 10X slower?
How do we explain the use of a software on a math paper?
Could sodium in ethanol reduce amides to amines?
how to create an executable file for an AppleScript?
Failing students when it might cause them economic ruin
What's is the easiest way to purchase a stock and hold it
Merging two rows with rounding their first elemnts
Number Sequence Series-Question 2
How can sister protect herself from impulse purchases with a credit card?
FIFO data structure in pure C
Can I get the output of a command line program with TeX (using e.g. read18)?
Async function without await in Javascript
Using async without awaitJavascript: await function endend before loop continueHow do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?How do I remove a property from a JavaScript object?var functionName = function() vs function functionName() Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have two functions a
and b
that are asynchronous, the former without await
and the later with await
. They both log something to the console and return undefined
. After calling either of the function I log another message and look if the message is written before or after executing body of the function.
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
If you launch test without await
the function seems to work as if it was synchronous. But with await
, the message are inverted as the function is executed asynchronously.
So my question is: how javascript execute async
functions when no await
keyword is present?
Real use case: I have an await
keyword which is conditionnaly executed, and I need to know if the function is executed synchronously or not in order to render my element:
async function initializeComponent(stuff)
if (stuff === undefined)
stuff = await getStuff()
// initialize
if (/* context has been blocked */)
renderComponent() // render again if stuff had to be loaded
initializeComponent()
renderComponent()
P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)
javascript asynchronous async-await
add a comment |
I have two functions a
and b
that are asynchronous, the former without await
and the later with await
. They both log something to the console and return undefined
. After calling either of the function I log another message and look if the message is written before or after executing body of the function.
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
If you launch test without await
the function seems to work as if it was synchronous. But with await
, the message are inverted as the function is executed asynchronously.
So my question is: how javascript execute async
functions when no await
keyword is present?
Real use case: I have an await
keyword which is conditionnaly executed, and I need to know if the function is executed synchronously or not in order to render my element:
async function initializeComponent(stuff)
if (stuff === undefined)
stuff = await getStuff()
// initialize
if (/* context has been blocked */)
renderComponent() // render again if stuff had to be loaded
initializeComponent()
renderComponent()
P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)
javascript asynchronous async-await
You also need to convertbButton.onclick
function into an async function and await forb()
to end in order to get the desired log.
– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not usingawait
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.
– Ulysse BN
Aug 9 '17 at 15:24
add a comment |
I have two functions a
and b
that are asynchronous, the former without await
and the later with await
. They both log something to the console and return undefined
. After calling either of the function I log another message and look if the message is written before or after executing body of the function.
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
If you launch test without await
the function seems to work as if it was synchronous. But with await
, the message are inverted as the function is executed asynchronously.
So my question is: how javascript execute async
functions when no await
keyword is present?
Real use case: I have an await
keyword which is conditionnaly executed, and I need to know if the function is executed synchronously or not in order to render my element:
async function initializeComponent(stuff)
if (stuff === undefined)
stuff = await getStuff()
// initialize
if (/* context has been blocked */)
renderComponent() // render again if stuff had to be loaded
initializeComponent()
renderComponent()
P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)
javascript asynchronous async-await
I have two functions a
and b
that are asynchronous, the former without await
and the later with await
. They both log something to the console and return undefined
. After calling either of the function I log another message and look if the message is written before or after executing body of the function.
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
If you launch test without await
the function seems to work as if it was synchronous. But with await
, the message are inverted as the function is executed asynchronously.
So my question is: how javascript execute async
functions when no await
keyword is present?
Real use case: I have an await
keyword which is conditionnaly executed, and I need to know if the function is executed synchronously or not in order to render my element:
async function initializeComponent(stuff)
if (stuff === undefined)
stuff = await getStuff()
// initialize
if (/* context has been blocked */)
renderComponent() // render again if stuff had to be loaded
initializeComponent()
renderComponent()
P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
function someMath()
for (let i = 0; i < 3000000; i++) Math.sqrt(i**5)
function timeout(n)
return new Promise(cb => setTimeout(cb, n))
// ------------------------------------------------- a (no await)
async function a()
someMath()
console.log('in a (no await)')
// ---------------------------------------------------- b (await)
async function b()
await timeout(100)
console.log('in b (await)')
clear.onclick = console.clear
aButton.onclick = function()
a()
console.log('after a (no await) call')
bButton.onclick = function()
b()
console.log('after b (await) call')
<button id="aButton">test without await</button>
<button id="bButton">test with await</button>
<button id="clear">clear console</button>
javascript asynchronous async-await
javascript asynchronous async-await
edited Feb 4 at 13:33
Ulysse BN
asked Aug 9 '17 at 15:15
Ulysse BNUlysse BN
2,72211436
2,72211436
You also need to convertbButton.onclick
function into an async function and await forb()
to end in order to get the desired log.
– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not usingawait
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.
– Ulysse BN
Aug 9 '17 at 15:24
add a comment |
You also need to convertbButton.onclick
function into an async function and await forb()
to end in order to get the desired log.
– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not usingawait
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.
– Ulysse BN
Aug 9 '17 at 15:24
You also need to convert
bButton.onclick
function into an async function and await for b()
to end in order to get the desired log.– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
You also need to convert
bButton.onclick
function into an async function and await for b()
to end in order to get the desired log.– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not using
await
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.– Ulysse BN
Aug 9 '17 at 15:24
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not using
await
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.– Ulysse BN
Aug 9 '17 at 15:24
add a comment |
3 Answers
3
active
oldest
votes
from mozilla doc:
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description
1
is there an eslint rule for redundantasync
keyword? I dont think synchronous functions should have it
– Blauhirn
Jan 17 '18 at 17:24
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
One benefit to declaring 'async' in a function that returns a promise but doesn't useawait
is that exceptions will be rejected instead of synchronously thrown. e.g.const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
|
show 3 more comments
Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await
is asynchronous and everything after await is placed in event queue. Similar to .then()
.
To better explain take this example:
function main()
return new Promise( resolve =>
console.log(3);
resolve(4);
console.log(5);
);
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(6);
As await
is asynchronous and rest all is synchronous including promise thus output is
1
2
3
5
6
// Async happened, await for main()
4
Similar behavior of main()
is without promise too:
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
5
// Asynchronous happened, await for main()
4
Just removing await
will make whole async
function synchronous which it is.
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
4
5
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used insideasync
function.
– NAVIN
Mar 7 at 5:44
add a comment |
The function is executed the same with or without await
. What await
does is automatically wait for the promise that's returned by the function to be resolved.
await timeout(1000);
more code here;
is roughly equivalent to:
timeout(1000).then(function()
more code here;
);
The async function
declaration simply makes the function automatically return a promise that's resolved when the function returns.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45594596%2fasync-function-without-await-in-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
from mozilla doc:
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description
1
is there an eslint rule for redundantasync
keyword? I dont think synchronous functions should have it
– Blauhirn
Jan 17 '18 at 17:24
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
One benefit to declaring 'async' in a function that returns a promise but doesn't useawait
is that exceptions will be rejected instead of synchronously thrown. e.g.const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
|
show 3 more comments
from mozilla doc:
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description
1
is there an eslint rule for redundantasync
keyword? I dont think synchronous functions should have it
– Blauhirn
Jan 17 '18 at 17:24
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
One benefit to declaring 'async' in a function that returns a promise but doesn't useawait
is that exceptions will be rejected instead of synchronously thrown. e.g.const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
|
show 3 more comments
from mozilla doc:
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description
from mozilla doc:
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description
edited Mar 23 at 17:34
answered Aug 9 '17 at 15:27
KarimKarim
5,7251826
5,7251826
1
is there an eslint rule for redundantasync
keyword? I dont think synchronous functions should have it
– Blauhirn
Jan 17 '18 at 17:24
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
One benefit to declaring 'async' in a function that returns a promise but doesn't useawait
is that exceptions will be rejected instead of synchronously thrown. e.g.const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
|
show 3 more comments
1
is there an eslint rule for redundantasync
keyword? I dont think synchronous functions should have it
– Blauhirn
Jan 17 '18 at 17:24
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
One benefit to declaring 'async' in a function that returns a promise but doesn't useawait
is that exceptions will be rejected instead of synchronously thrown. e.g.const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
1
1
is there an eslint rule for redundant
async
keyword? I dont think synchronous functions should have it– Blauhirn
Jan 17 '18 at 17:24
is there an eslint rule for redundant
async
keyword? I dont think synchronous functions should have it– Blauhirn
Jan 17 '18 at 17:24
1
1
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
Maybe this one: eslint.org/docs/rules/require-await
– Karim
Jan 17 '18 at 18:55
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
oh yes, thats the one. missed it somehow :D thank you
– Blauhirn
Jan 17 '18 at 18:57
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
No problem, you're welcome ;)
– Karim
Jan 17 '18 at 19:02
5
5
One benefit to declaring 'async' in a function that returns a promise but doesn't use
await
is that exceptions will be rejected instead of synchronously thrown. e.g. const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
One benefit to declaring 'async' in a function that returns a promise but doesn't use
await
is that exceptions will be rejected instead of synchronously thrown. e.g. const result = someAsyncFunctionWithoutAwait().catch(handleRejection)
– aaaaaa
Apr 30 '18 at 23:09
|
show 3 more comments
Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await
is asynchronous and everything after await is placed in event queue. Similar to .then()
.
To better explain take this example:
function main()
return new Promise( resolve =>
console.log(3);
resolve(4);
console.log(5);
);
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(6);
As await
is asynchronous and rest all is synchronous including promise thus output is
1
2
3
5
6
// Async happened, await for main()
4
Similar behavior of main()
is without promise too:
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
5
// Asynchronous happened, await for main()
4
Just removing await
will make whole async
function synchronous which it is.
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
4
5
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used insideasync
function.
– NAVIN
Mar 7 at 5:44
add a comment |
Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await
is asynchronous and everything after await is placed in event queue. Similar to .then()
.
To better explain take this example:
function main()
return new Promise( resolve =>
console.log(3);
resolve(4);
console.log(5);
);
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(6);
As await
is asynchronous and rest all is synchronous including promise thus output is
1
2
3
5
6
// Async happened, await for main()
4
Similar behavior of main()
is without promise too:
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
5
// Asynchronous happened, await for main()
4
Just removing await
will make whole async
function synchronous which it is.
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
4
5
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used insideasync
function.
– NAVIN
Mar 7 at 5:44
add a comment |
Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await
is asynchronous and everything after await is placed in event queue. Similar to .then()
.
To better explain take this example:
function main()
return new Promise( resolve =>
console.log(3);
resolve(4);
console.log(5);
);
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(6);
As await
is asynchronous and rest all is synchronous including promise thus output is
1
2
3
5
6
// Async happened, await for main()
4
Similar behavior of main()
is without promise too:
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
5
// Asynchronous happened, await for main()
4
Just removing await
will make whole async
function synchronous which it is.
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
4
5
Everything is synchronous until a Javascript asynchronous function is executed. In using async-await await
is asynchronous and everything after await is placed in event queue. Similar to .then()
.
To better explain take this example:
function main()
return new Promise( resolve =>
console.log(3);
resolve(4);
console.log(5);
);
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(6);
As await
is asynchronous and rest all is synchronous including promise thus output is
1
2
3
5
6
// Async happened, await for main()
4
Similar behavior of main()
is without promise too:
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = await main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
5
// Asynchronous happened, await for main()
4
Just removing await
will make whole async
function synchronous which it is.
function main()
console.log(3);
return 4;
async function f()
console.log(2);
let r = main();
console.log(r);
console.log(1);
f();
console.log(5);
Output:
1
2
3
4
5
edited Dec 12 '18 at 5:28
answered Dec 11 '18 at 18:50
NAVINNAVIN
1,8173826
1,8173826
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used insideasync
function.
– NAVIN
Mar 7 at 5:44
add a comment |
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used insideasync
function.
– NAVIN
Mar 7 at 5:44
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
You could add also a function that does var g = await f() since f() is async and perhaps would need to be awaited on a long running process if you dont want to block the main executing thread.
– flux9998
Jan 4 at 0:05
await
can only be used inside async
function.– NAVIN
Mar 7 at 5:44
await
can only be used inside async
function.– NAVIN
Mar 7 at 5:44
add a comment |
The function is executed the same with or without await
. What await
does is automatically wait for the promise that's returned by the function to be resolved.
await timeout(1000);
more code here;
is roughly equivalent to:
timeout(1000).then(function()
more code here;
);
The async function
declaration simply makes the function automatically return a promise that's resolved when the function returns.
add a comment |
The function is executed the same with or without await
. What await
does is automatically wait for the promise that's returned by the function to be resolved.
await timeout(1000);
more code here;
is roughly equivalent to:
timeout(1000).then(function()
more code here;
);
The async function
declaration simply makes the function automatically return a promise that's resolved when the function returns.
add a comment |
The function is executed the same with or without await
. What await
does is automatically wait for the promise that's returned by the function to be resolved.
await timeout(1000);
more code here;
is roughly equivalent to:
timeout(1000).then(function()
more code here;
);
The async function
declaration simply makes the function automatically return a promise that's resolved when the function returns.
The function is executed the same with or without await
. What await
does is automatically wait for the promise that's returned by the function to be resolved.
await timeout(1000);
more code here;
is roughly equivalent to:
timeout(1000).then(function()
more code here;
);
The async function
declaration simply makes the function automatically return a promise that's resolved when the function returns.
answered Aug 9 '17 at 15:26
BarmarBarmar
444k36264370
444k36264370
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45594596%2fasync-function-without-await-in-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
You also need to convert
bButton.onclick
function into an async function and await forb()
to end in order to get the desired log.– Jose Hermosilla Rodrigo
Aug 9 '17 at 15:23
@JoseHermosillaRodrigo I don't want to wait for the desired log, I want to know with using or not using
await
keyword alters the synchronous function. And if it does not, maybe why my test is wrong. I'll update with my real use case at the end, maybe it'll be clearer for you.– Ulysse BN
Aug 9 '17 at 15:24