I am using async/await in several places in my code.
For example, if I have this function:
async function func(x) {
...
return y;
}
Then I always call it as follows:
async function func2(x) {
let y = await func(x);
...
}
I have noticed that in some cases, I can omit the await and the program will still run correctly, so I cannot quite figure out when I must use await and when I can drop it.
I have concluded that it is "legitimate" to drop the await only directly within a return statement.
For example:
async function func2(x) {
...
return func(x); // instead of return await func(x);
}
Is this conclusion correct, or else, what am I missing here?
EDIT:
A small (but important) notion that has not been mentioned in any of the answers below, which I have just encountered and realized:
It is NOT "legitimate" to drop the await within a return statement, if the called function may throw an exception, and that statement is therefore executed inside a try block.
For example, removing the await in the code below is "dangerous":
async function func1() {
try {
return await func2();
}
catch (error) {
return something_else;
}
}
The reason is that the try block completes without an exception, and the Promise object returns "normally". In any function which calls the outer function, however, when this Promise object is "executed", the actual error will occur and an exception will be thrown. This exception will be handled successfully in the outer function only if await is used. Otherwise, that responsibility goes up, where an additional try/catch clause will be required.
If func is an async function then calling it with and without await has different effects.
async function func(x) {
return x;
}
let y = await func(1); // 1
let z = func(1) // Promise (resolves to 1)
It is always legitimate to omit the await keyword, but means you will have to handle the promises in the traditional style instead (defeating the point of async/await in the first place).
func(1).then(z => /* use z here */)
If your return statements use await then you can be sure that if it throws an error it can be caught inside your function, rather than by the code that calls it.
await just lets you to treat promises as values, when used inside an async function.
On the other hand, async works quite the opposite, it tags the function to return a promise, even if it happens to return a real, synchronous value (which sounds quite strange for an async function... but happens often when you have a function that either return a value or a promise based on conditions).
So:
I have concluded that it is "legitimate" to drop the await only directly within a return statement.
In the last return statement of an async function, you just are returning a Promise, either you are return actually a directly a promise, a real value, or a Promise-as-value with the await keyword.
So, is pretty redundant to use await in the return statement: you're using await to cast the promise to a value -in the context of that async execution-, but then the async tag of the function will treat that value as a promise.
So yes, is always safe to drop await in the last return statement.
PS: actually, await expects any thenable, i.e. an object that has a then property: it doesn't need a fully spec compliant Promise to work, afaik.
PS2: of course, you can always drop await keyword when invoking synchronous functions: it isn't needed at all.
An async function always returns a Promise.
So please keep in mind that these writing of an async function are all the same:
// tedious, sometimes necessary
async function foo() {
return new Promise((resolve) => resolve(1)))
}
// shorter
async function foo() {
return Promise.resolve(1)
}
// very concise but calling `foo` still returns a promise
async function foo() {
return 1 // yes this is still a promise
}
You call all of them via foo().then(console.log) to print 1. Or you could call them from another async function via await foo(), yet it is not always necessary to await the promise right away.
As pointed out by other answers, await resolves the promise to the actual return value statement on success (or will throw an exception on fail), whereas without await you get back only a pending promise instance that either might succeed or fail in the future.
Another use case of omitting (i.e.: being careful about its usage) await is that you might most likely want to parallelize tasks when writing async code. await can hinder you here.
Compare these two examples within the scope of an async function:
async function func() {
const foo = await tediousLongProcess("foo") // wait until promise is resolved
const bar = await tediousLongProcess("bar") // wait until promise is resolved
return Promise.resolve([foo, bar]) // Now the Promise of `func` is marked as a success. Keep in mind that `Promise.resolve` is not necessary, `return [foo, bar]` suffices. And also keep in mind that an async function *always* returns a Promise.
}
with:
async function func() {
promises = [tediousLongProcess("foo"), tediousLongProcess("bar")]
return Promise.all(promises) // returns a promise on success you have its values in order
}
The first will take significantly longer than the last one, as each await as the name implies will stop the execution until you resolve the first promise, then the next one.
In the second example, the Promise.all the promises will be pending at the same time and resolve whatever order, the result will then be ordered once all the promises have been resolved.
(The Bluebird promise library also provides a nice Bluebird.map function where you can define the concurrency as Promise.all might cripple your system.)
I only use await when want to work on the actual values. If I want just a promise, there is no need to await its values, and in some cases it may actually harm your code's performance.
I got a good answer above, here is just another explanation which has occurred to me.
Suppose I have this:
async function func(x) {
...
return y;
}
async function func2(x) {
...
return await func(x);
}
async function func3(x) {
let y = await func2(x);
...
}
The reason why I can safely remove the await in the return statement on func2, is that I already have an await when I call func2 in func3.
So essentially, in func3 above I have something like await await func(x).
Of course, there is no harm in that, so it's probably better to keep the await in order to ensure desired operation.
Related
I have a promise stored in a const
const goToWork = new Promise((resolve, reject) => {
setTimeout(() => resolve('Go to Work'));
});
since calling goToWork() would error expression is not callable
I tried storing running it in an async function:
async function callPromise() {
return await goToWork;
}
now awaiting callPromise as such await callPromise() returns pending<Promise> which tempted me to store it in another async function as such:
async function executePromise() {
console.log(await callPromise());
}
and then ran it executePromise()
// output: Go To Work
my question is how come executePromise() didn't complain of not running in an async function ? how come it did not need to be "awaited"
I tried storing running it in an async function:
There really is no point at all this this function:
async function callPromise() {
return await goToWork;
}
It absolutely the same as:
function callPromise() {
return goToWork;
}
which is a pointless function that doesn't do anything useful. So, since you're making a function with no practical use, there must be some basic misunderstanding of async/await.
To start with, all async function return a promise - always. So, return await fn() is not useful. You may as well just do return fn(). Both return a promise with the same state.
now awaiting callPromise as such await callPromise() returns pending which tempted me to store it in another async function as such:
Yes, as I said above. All async functions return a promise.
and then ran it executePromise() // output: Go To Work
There should be no surprise here.
console.log(await callPromise());
This will output the result of await callPromise() which (if it doesn't reject) will output the resolved value of the promise that callPromise() returns.
my question is how come executePromise() didn't complain of not running in an async function ? how come it did not need to be "awaited"
Here's your executePromise function:
async function executePromise() {
console.log(await callPromise());
}
There's no problem with this function because the await is inside an async function. That follows the async/await rules.
When you call it like this:
executePromise()
That just runs the function and because that function is an async function, it will always return a promise. There is no rule that calling an async function requires using await on it or must be called from within another async function.
You can call it like this:
executePromise().then(...).catch(...)
Or, you can put it in a async function:
async someFunction() {
try {
await executePromise();
} catch(e) {
// got error
console.log(e);
}
}
Or, you can just call it without regard for the returned promise:
executePromise();
Calling it naked like this last one is not paying any attention to whether the returned promise resolves or rejects and is not paying any attention to any resolved value. But, it's legal to do this. It possibly sets you up for an unresolved rejection because there's no reject handler, but if you know that promise will never reject and you don't care when it resolves or what the resolved value is, then this is allowed.
my question is how come executePromise() didn't complain of not running in an async function?
But it did run in an async function: async function executePromise().
Keep in mind that await is syntactic sugar (more or less, see comments), and you can always turn it back into Promise.then(), where this:
const x = await Promise.resolve('foo')
console.log(x)
behaves similar to
Promise.resolve('foo').then(x => console.log(x))
This makes it easy to understand what is going on:
async function callPromise() {
return await goToWork;
}
is similar to
async function callPromise() {
return goToWork.then(x => x);
}
And
console.log(await callPromise());
can be thought of as
goToWork.then(x => x).then(x => console.log(x))
None of that needs to be awaited, but you can use await to make it more readable.
I was discussing with someone else about the use of async/await in JavaScript and we didn't agree.
Personally, I only use await when I need to wait for the async method to be finished. If I don't need it to finish to continue, I don't.
E.g.:
async myAsyncMethod() {
axios.get(`/foo`)
.then((response) => {
this.foo = response.data;
}).catch (exception) {
//do something with exception
this.foo = null;
};
}
If I need the data right away, I call:
await myAsyncMethod();
If I don't, I do:
myAsyncMethod();
Is it not correct to do this last one? The other person maintained that I should not. If so, would it be possible to explain to me why.
I've edited the myAsyncMethod() to be more precise. So my questions implies that that I catch errors and that I know that 'foo' is either null either field with data at some point... The point is that I don't need those data right away and I've got other things to do that don't require it.
An async function without an await expression will run synchronously.
The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.
So, in your case, the myAsyncMethod will return an unsettled promise unless you await it.
References:
Async function
Await operator
I'm following along an MDN article on async/await, and I understand the purpose of using the async keyword before functions, but I'm a little more confused about the await keyword. I've read up on on "await" as a result, and I get the general concept, but I'm still unsure when it comes to examples. For instance, here is a trivial piece of code (as shown in the MDN article) using async/await.
async function hello() {
return greeting = await Promise.resolve("Hello");
};
hello().then(value => console.log(value));
As you might expect, this logs "Hello" to the console. But even if we omit "await", it has the exact same output.
async function hello() {
return greeting = Promise.resolve("Hello"); // without await
};
hello().then(value => console.log(value));
Can someone help me understand exactly what the await keyword before Promise.resolve is doing? Why is the output the same even if it's omitted? Thanks.
In up-to-date JavaScript engines, there's no difference, but only because the return await somePromise is at the top level of the function code. If it were within a control block (for instance, try/catch), it would matter.
This is a recent-ish change. Until ES2020 the return await version would have introduced an extra async "tick" into the process. But that was optimized out in a "normative change" (rather than proposal) in ES2020 when the promise being awaited is a native promise. (For a non-native thenable, there's still a small difference.)
For the avoidance of doubt, there's an important difference between:
async function example() {
try {
return await somethingReturningAPromise();
} catch (e) {
// ...do something with the error/rejection...
}
}
and
async function example() {
try {
return somethingReturningAPromise();
} catch (e) {
// ...do something with the error/rejection...
}
}
In the former, a rejection of the promise from somethingReturningAPromise() goes to the catch block, because it's been awaited. In the latter, it doesn't, because you've just returned the promise, which resolves the promise from the async function to the promise somethingReturningAPromise() returns, without subjecting it to the catch.
But in your example, where it's not in any control structure, the await is largely a matter of style at this point.
Keep in mind that async/await is just a fancy API for working with promises.
An async function always and implicitly returns a promise (as soon as the first await or return statement is reached) that will be resolved when the function code itself finally reaches its end. The resolved promise value will be equal to the function's returned value.
async allows you to use await inside of the asynchronous scope. Await only makes sense when preceding a promise (could be another async function call, a promise created in place with new Promise(), etc.). Using await before non promise values will do no harm though.
await indicates, just that, wait. It tells the engine to 'stop' code execution on that scope and to resume it whenever the promise is fulfilled. await will then give you or 'return' the promise resolved value.
Just to give you some practical examples:
Using your first code:
async function hello() {
const greeting = await Promise.resolve("Hello"); // HERE I CAN USE await BECAUSE I'M INSIDE AN async SCOPE.
console.log('I will be printed after above promise is resolved.');
return greeting;
};
hello().then(value => console.log(value));
Using your second code, async could be completely removed:
function hello() {
return Promise.resolve("Hello");
};
hello().then(value => console.log(value));
Please let me know if there is any doubt.
I have been reading up on async/await in Node.js. I have learnt that the await keyword waits for a promise to be resolved, or throws an exception if it was rejected.
I have also learnt that every function that wants to use await needs to be marked async. However, what does it mean for a function to be marked async?
All the resources and blog posts I was able to find seem to explain await in great detail, but ignore the concept of an async function, or briefly gloss over it. For instance, this author puts it like this:
This makes the function return a Promise implicitly.
What does the async keyword really do? What does it mean for a function to implicitly return a Promise? What are the side effects other than being able to use await?
Alright, so from the answers I have received so far it's clear that it simply wraps the function's return value into a Promise, much like Promise.then would. That just leaves a new question though. Why does a function that uses await need to be async and thus return a Promise?
No matter what you actually return from your function, your async function will still return a Promise. If you return a Number, it actually returns a Promise that resolves to the Number your originally returned. This allows you to write synchronous "looking" code.
Rather than having to write out this:
function foo(){
return Promise.resolve("foo");
}
You can just write this:
async function foo(){
return "foo";
}
and foo() will automagically return a Promise that resolves to "foo".
In response to you comment:
Does it behave like Promise.then in the sense that if you already
return a Promise, it won't wrap it again?
await will peel the Promise until it gets to a value:
async function foo() {
return Promise.resolve(Promise.resolve(true));
}
async function bar() {
return true;
}
(async function () {
let tmp;
tmp = await foo();
console.log(tmp);
tmp = await bar();
console.log(tmp);
console.log("Done");
}());
/*
Prints:
true
true
Done
*/
Why is async needed?
Paraphrasing from #KevinB's comment.
await, just like yield in a generator, pauses the execution of that context until the Promise it's waiting on is no longer pending. This cannot happen in normal functions.
If a function is async but does not contain an await, the promise will be resolved immediately, and any callbacks will be ran on the next tick.
What does async do?
async is syntactic sugar for making your method chain Promise objects.
Take the following method for example:
async function myFunction(a)
{
if (a == 10)
{
await otherFunction();
}
return 10;
}
The JavaScript runtime you use might make more optimized code, but in its simplest it will be something along the lines:
function myFunction(a)
{
if (a === 10)
{
return otherFunction()
.then(() => myFunction_continuation());
}
else
{
return myFunction_continuation();
}
function myFunction_continuation()
{
return Promise.resolve(10);
}
}
For documentation on the Promise type I recommend checking out the Mozilla Developer Network page about the Promise type .
Why do you need to mark it async? Why not just use await?
Because your method needs to be split up into multiple "parts" for it to be able to have code execute after the method being awaited on. The example above has a single continuation, but there could be multiple.
The designers of JavaScript want to make it visible to the developer that the runtime is doing this "magic". But maybe the most important reason is that they don't want to break existing code using await as a variable name. They do this by making await a "contextual keyword". A "contextual keyword" is only a keyword in specific scenarios, in this case: when used inside a method marked as async:
function ABC()
{
var await = 10;
}
The above compiles. But if I add the async keyword to the function declaration it no longer does and throws an Uncaught SyntaxError: Unexpected reserved word.
Asynchronous Task Running
The Basic idea is to use a function marked with async instead of a generator and use await instead of yield when calling a function, such as:
(async function() {
let contents = await readFile('config.json');
doSomethingWith(contents);
console.log('Done');
});
The Async Keyword before function indicates that the function is meant to run in an asynchronous manner. The await keyword signals that the function call to readFile('config.json') should return a promise, and if it doesn't, the response should be wrapped in a promise.
The end result is that you can write asynchronous code as if it were synchronous without overhead of managing an iterator-based state machine.
Understanding ECMACSCRIPT 6 by Nicholas c. Zakas
I see there is an eslint rule, no-return-await, for disallowing return await.
In the rule's description, it states a return await adds "extra time before the overarching Promise resolves or rejects".
However, when I look at MDN async function docs, the "Simple Example" shows an example containing return await without any description of why this might be a performance problem.
Is return await an actual performance problem as the eslint docs suggest?
And if so, how?
No, there isn't any performance problem. It's just an unnecessary extra operation. It might take a bit longer to execute, but should be hardly noticeable. It's akin to return x+0 instead of return x for an integer x. Or rather, exactly equivalent to the pointless .then(x => x).
It doesn't do actual harm, but I'd consider it bad style and a sign that the author does not fully comprehend promises and async/await.
However, there's one case where it make an important difference:
try {
…
return await …;
} …
await does throw on rejections, and in any case awaits the promise resolution before catch or finally handlers are executed. A plain return would have ignored that.
I'm adding an answer because a comment would be too long. I originally had a very long, verbose explanation about how async works and await work. But it's just so convoluted that actual data may just be easier to understand. So here is the, uh, simplified explanation. Note: This is run on Chrome v97, FireFox v95, and Node v16 with the same results.
The answer as to what's faster: it depends on what you're returning and how you're calling it. await works differently than async because it runs PromiseResolve (similar to Promise.resolve but it's internal). Basically, if you run await on a Promise (a real one, not a polyfill), await doesn't try to wrap it. It executes the promise as is. That skips a tick. This is a "newer" change from 2018. In summary, evaluating await always returns the result of a Promise, not a Promise, while avoiding wrapping Promises when possible. That means await always takes at least one tick.
But that's await and async doesn't actually use this bypass. Now async uses the good ol' PromiseCapability Record. We care about how this resolves promises. The key points are it'll instantly start fulfilling if the resolution is "not an Object" or if .then is not Callable. If neither are true, (you're returning a Promise), it'll perform a HostMakeJobCallback and tack on to the then in the Promise, which basically means, we're adding a tick. Clarified, if you return a Promise in an async function, it'll add on an extra tick, but not if you return a Non-Promise.
So, with all that preface (and this is the simplified version), here's your chart as to how many ticks until your await foo() call is returned:
Non-Promise
Promise
() => result
1
1
async () => result
1
3
async () => await result
2
2
This is tested with await foo(). You can also test with foo().then(...), but the ticks are the same. (If you don't use an await, then the sync function would indeed be 0. Though foo().then would crash, so we need something real to test with.) That means our floor is 1.
If you understood my explanations above (hopefully), this will make sense. The sync function makes sense because at no point in the function do we call for paused execution: await foo() will take 1 tick.
async likes Non-Promises and expects them. It will return immediately if it finds one. But if it finds a Promise, it'll tack on to that Promise's then. That means it'll execute the Promise (+1) and then wait for the then to complete (another +1). That's why it's 3 ticks.
await will convert a Promise to a Non-Promise which is perfect for async. If you call await on a Promise, it'll execute it without tacking any extra ticks (+1). But, await will convert a Non-Promise into a Promise and then run it. That means await always takes a tick, regardless of what you call it against.
So, in conclusion, if you want the fastest execution, you want to make sure your async function always includes at least one await. If it doesn't, then just make it synchronous. You can always call await on any synchronous function. Now, if you want to really tweak performance, and you are going to use async, you have to make sure always return a Non-Promise, not a Promise. If you are returning a Promise, convert it first with await. That said you can mix and match like this:
async function getData(id) {
const cache = myCacheMap.get(id);
if (cache) return cache; // NonPromise returns immediately (1 tick)
// return fetch(id); // Bad: Promise returned in async (3 ticks)
return await fetch(id); // Good: Promise to NonPromise via await (2 ticks)
}
With that in mind, I have a bunch of code to rewrite :)
References:
https://v8.dev/blog/fast-async
https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-async-functions-abstract-operations-async-function-start
Test:
async function test(name, fn) {
let tick = 0;
const tock = () => tick++;
Promise.resolve().then(tock).then(tock).then(tock);
const p = await fn();
console.assert(p === 42);
console.log(name, tick);
}
await Promise.all([
test('nonpromise-sync', () => 42),
test('nonpromise-async', async () => 42),
test('nonpromise-async-await', async () => await 42),
test('promise-sync', () => Promise.resolve(42)),
test('promise-async', async () => Promise.resolve(42)),
test('promise-async-await', async () => await Promise.resolve(42)),
]);
setTimeout(() => {}, 100);