I have two asynchronous methods that return values, one of which is needed immediately and the other might be in use, based on the first result. However, I don't want to wait for the first result to come in before kicking off the second method and create an execution sequence dependency.
Using ES7 syntax, I would assume that await-ing a Promise would be the same as await-ing a function that returns a Promise, but it doesn't work:
async function tester() {
async function foo() { await setTimeout(() => {}, 2000)}
async function bar() { await setTimeout(() => {}, 1000)}
let rcFoo = foo();
let rcBar = await bar();
if (true) { // Some conditional based on rcBar
await rcFoo;
console.log(rcFoo); // It's a Promise object
}
}
Two questions:
Am I even understanding the asynchronous nature of Javascript correctly? If the above code would have worked, would it have achieved my goal of running two asynchronous functions concurrently-ish, or is it just not possible to do it?
Is it possible to somehow await an object that is a Promise like I tried, or does it have to reference a function directly?
Thanks..
In your code, foo will start right away, and then bar will start. Even if foo finished first, your code still awaits for the bar promise to finish before proceeding.
You can await everything as long as it's a promise, whether it's a variable or a returned value from a function call. As far as I know (I might be wrong), setTimeout doesn't return a promise, but it would be easy to convert it to one:
async function foo() {
return new Promise(resolve => setTimeout(resolve, 2000))
}
async function bar() {
return new Promise(resolve => setTimeout(resolve, 1000))
}
I would assume that await-ing a Promise would be the same as await-ing a function that returns a Promise
The same as awaiting the result of a call to a function that returns a promise, yes (which is awaiting a promise).
but it doesn't work:
await rcFoo;
console.log(rcFoo); // It's a Promise object
It does work, only awaiting a variable doesn't change that variable. You can only await values, and the result of the promise will become the result value of the await expression:
let res = await promise;
console.log(res); // a value
console.log(promise) // a promise for the value
That said, setTimeout doesn't return a promise, so your code doesn't sleep three seconds. You will have to promisify it, like e.g. #PedroMSilva showed it.
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 sort of understand what each is doing. setTimeout, "The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds." Async await, returns a promise, and is just a function that can be put in a queue and have the results of the function checked in later.
But both allow me to "delay code", they are both asynchronous functions. So when would you use one rather than the other one?
Thank you for any help!
They are completely different.
Using async/await allows you to consume Promises in a flat manner in your code, without nesting callbacks or hard-to-read .then chains. For example:
const doSomething = async () => {
await asyncStep1();
await asyncStep2();
await asyncStep3();
};
where each async step returns a Promise.
await only allows you to "delay" code in a block if you already have a Promise to work with (or something that you convert to a Promise).
setTimeout is not similar at all to async/await - setTimeout doesn't consume a Promise or have anything to do with Promises at all. setTimeout allows you to queue a callback to be called later, after the timeout time has finished.
Unlike await, setTimeout does not delay code in a block - rather, you pass it a callback, and the callback gets called later.
Cool question.
You're right that they're both asynchronous code.
As a simple answer to the difference. If you are doing something like:
const fetchUser = async () => {
const result = await fetch("/user");
return await result.json();
}
async main1() {
setTimeout(() => console.log("done", 2000));
}
async main2() {
await fetchUser();
console.log("done");
}
The setTimeout is always going to take ~2000ms before it logs "done", provided you haven't blocked the thread somewhere else. The fetchUser is going to log "done" when the API is complete, that might be 100ms, that might be 10000ms.
But the difference is a bit more involved than that:
It's partly to do with the difference in a callback style of code or a promise style of code.
The callback style is an older of coding, the difference here is a bit more than that.
Let's set aside setTimeout for a moment and talk about two ways you might make a fetch call.
const fetchUserOne = async() => {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await result.json();
return json;
}
const fetchUserTwo = () => {
return fetch('https://jsonplaceholder.typicode.com/todos/2')
.then(response => response.json())
};
async function main() {
const result1 = fetchUserOne();
const result2 = fetchUserTwo();
console.log(result1);
console.log(result2)
const awaitedResult1 = await result1;
const awaitedResult2 = await result2;
console.log(awaitedResult1);
console.log(awaitedResult2);
}
main().then(console.log("complete"));
Now what I want to highlight here, is that although the second example uses a callback style - they are both using promises.
When you run the code (and press F12 to see the full object), you'll note that the log of result1 and result2 are promises.
Window.setTimeout on the other hand does not use a Promise.
const result = setTimeout(() => {
console.log("done");
}, 2000);
console.log(result);
The return value of the setTimeout is a number, which can be used to cancel the timeout.
And that brings us to the main difference:
Promises are not cancellable, setTimeout is
See this Stack Overflow question about cancelling a promise.
To show an example of this, let's modify our example above.
const fetchUser = async () => {
const result = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return await result.json();
}
let timeout;
async function main1() {
console.log("start main1");
timeout = setTimeout(() => console.log("done timeout"), 2000);
}
async function main2() {
console.log("start main2");
await fetchUser();
console.log("done fetchuser");
}
main1();
main2();
clearTimeout(timeout);
Above, we can see that we can quite easily abort the timeout call, whereas we can't cancel a promise directly.
This is not to say that you can't cancel that fetch request, as you can see in this thread, but you can't cancel the promise itself.
Firstly, setTimeout is static timer that depends on the given time. On the other hand async await is something that is not static. It will wait until it awaited function or promise return any response or error
Secondly, You can Timeout any execution but you cannot await any function.
Here is the Official doc Async await
setTimeout allows you to delay execution for an approximate amount of time.
let log = () => console.log('log');
// invokes `log()` after a delay
setTimeout(log, 1000);
async/await helps you deal with promises without function handlers; it's just syntactic sugar. It doesn't actually delay execution.
let promise = Promise.resolve(5);
let main = async() => {
// without await
promise.then(value => console.log(value));
// with await
console.log(await promise);
};
main();
Both async await and setTimeout aren't similar eventhough it looks like they are but they aren't.
If you are new to JavaScript then, you can think of setTimeout as a timer, so whatever block of code or function is passed to setTimeout it will execute after a fixed time, it basically delays the execution of code, while on the other hand async await isn't bound to any timer, to understand simply, function or promise that uses async await will wait until the function or promise returns an appropriate response...
$ cat x.js
async function print() {
console.log("abc");
}
print();
$ nodejs x.js
abc
How can it be?! print() returns a Promise object that isn't awaited, is it? If it is not awaited, then why is the console.log executed?
yeah, like choz said ,async functions returns a promise, even if you haven't defined a promise in your code.
i think this returned promise turns fulfilled after all promises in await statement get resolved.
i test it in the following code, it also returns promise, which only turns fulfilled after all promises go resolved(after 3000ms in this case):
async function print2() {
await console.log("abc")
await new Promise((res, rej) => {
setTimeout(() => {res(33)},3000)
})
await new Promise((res, rej) => {
setTimeout(() => {res(33)},50)
})
}
You could say that an empty function itself, returns undefined (Which actually doesn't return anything). Take a look at the sample below;
function print() {}
var returnVal = print(); // undefined
You'll notice that returnVal is undefined.
Now, if we have something in the body of test() there, but you still don't pass any return value, then returnVal will still be undefined.
function print() {
console.log('abc');
}
var returnVal = print(); // undefined
So, in order for a function to have a return value, one simply just needs to return it.
function print() {
console.log('abc');
return 1;
}
var returnVal = print(); // 1
When you conver it to async function. Quoting from MDN
The body of an async function can be thought of as being split by zero
or more await expressions. Top-level code, up to and including the
first await expression (if there is one), is run synchronously. In
this way, an async function without an await expression will run
synchronously. If there is an await expression inside the function
body, however, the async function will always complete asynchronously.
Code after each await expression can be thought of as existing in a
.then callback. In this way a promise chain is progressively
constructed with each reentrant step through the function. The return
value forms the final link in the chain.
Now, based on the information above, here's what we know that refer to your question;
Your print() does not return anything, which should be undefined
The async function will complete asynchronously, meaning it will always return a Promise. Either pending, fulfilled or rejected
So, to say it in your question, here's what your function actually does;
async function print() {
console.log("abc"); // Prints 'abc'
}
// Function above is equivalent to;
function printEquivalentInNonAsync() {
console.log("abc"); // Prints 'abc'
}
var returnVal = print(); // `returnVal` is `undefined`
And, to answer your question
If it is not awaited, then why is the console.log executed?
Regardless the async function is awaited, it still executes! - Awaits just to ensure the line execution is halted until the Asynchronous function (Promise) has reached fulfilled or rejected. Note that, the first state of a Promise is pending.
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 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.