I'm a bit confused about the MDN documentation of async await. These docs use the .then() syntax to respond when an async function has resolved:
mdn example
async function add() {
const b = await resolveAfter2Seconds(30); // timer
return b;
}
add().then(v => {
console.log(v);
});
But in my own code, I don't use .then() and it still works asynchronously. The flow is not blocked. So why would you use .then() ?
async code without .then
function start(){
console.log("starting!")
let d = loadData()
console.log("this message logs before loadData returns!")
console.log(d) // this shows: Promise - Pending because d has not yet returned
}
async function loadData() {
const response = await fetch("https://swapi.co/api/films/");
const json = await response.json();
console.log("data loaded!")
return json;
}
First of all, all async functions return a Promise, so if you want to get the returned value from that async operation, you'll either need to use then or await inside an async function.
MDN uses .then because the add async function is being called outside an async function scope, so it can't use await globally to catch the data from the promise.
In your example, you get the same, an instance of Promise as the return of your loadData async function, if you define the start function also as async, you can use let d = await loadData(), if it's not async, you can use .then (which is the Promise API).
Async function declaration async function loadData() returns AsyncFunction which is executed asynchronously and always returns a Promise.
Basically all the code you put inside the async function someFunctionName will be executed inside that Promise and when you return some value inside that function – it will resolve that promise.
So that then() call is to get the actual value from that Promise that your function returned.
Your code works because it is not returning promise object and actually waiting for the response. It returns the json at the end. So, execution holds till it gets the response.
If your function is async you don't need to return promise, your return statement will wait for all 'await' statement before it to complete.
Your own code works, because you replaced the usage of .then() with the usage of async await.
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.
Here is an example:
let test = async () => {
let res = fetch('https://jsonplaceholder.typicode.com/todos/1')
}
console.log(test()) // Promise {<resolved>: undefined}
The output is Promise {<resolved>: undefined} because i didn't return anything, and it resolved with undefined. I understand this.
Now, here is the second example:
let test = async () => {
let res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
}
console.log(test()) // Promise {<pending>}
I'm still not returning anything, and i get Promise {<pending>}. Why is it happening ?
The difference is that in your first example, the fetch call is not awaited, and it simply returns a promise object that is assigned to the res variable, and then, the function immediately returns. The promise that fetch returns is lost.
The second example when you use the await keyword, the async function is "paused" to wait until the fetch call resolves, and it assigns the resolved value (the fetch response) to the variable.
Even if you are not returning anything, whenever you await a promise inside an async function, it will wait until it resolves or rejects.
If the promise you are awaiting rejects, it will cause an exception within the function that will end up in a rejection of the implicitly returned promise.
When we have an async function that returns a variable, and then .then() is run...
What does .then() accept as parameters?
Is it the variable that async returns?
For example, consider this node.js example:
const js_package = require('random_js_package');
var random_variable;
let js_function = async () => {
random_variable = js_package();
return random_variable;
}
js_function().then((value) => {
for (var i=0; i<value.length; i++){
console.log(value[i]);
}
});
In this case, is the variable called value inside .then() what the async function returns?
In other words, is value the same as random_variable?
The then function accepts two arguments:
a function to run if the promise is resolved
a function to run if the promise is rejected
The first function you pass to it needs to accept one argument:
The resolved value of a promise
Meanwhile, async functions returns:
A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.
So, aside from you confusing the then function with the function you pass to it: Yes.
When you declare a function with async the function will always return a promise. So if you don't explicitly return a promise from the async function then javascript will wrap the value you return in a promise. .then() always takes a function which has a parameter which is the resolved value of a promise. So your code is correct the way it is written. In your code value will equal random_variable. Behind the scenes javascript is returning a promise from js_function which is why using .then((value) => works.
When i run console.log (f ()) i want it returns the data that came from getData (url), but it keeps returning Promise {<pending>}. I thought using await keyword would solve this by making the code execution stops untilgetData ()returns something. I know if i use f().then(console.log) it will work fine, but i just don't understand why console.log (f()) does not works too.
There is a way to achieve the same result f().then(console.log) but not using the then () function?
async function f() {
const url = `https://stackoverflow.com`;
let d = await getData(url);
return d;
}
console.log(f());
If it is impossible, can you explain why?
f is an async function, so it still returns a Promise.
To wait for this promise to resolve you need to await it.
(async () => console.log(await f())();
Or in long:
async function run(){
console.log(await f());
}
run();
async and await do not stop functions from being asynchronous.
An async function will always return a Promise. It just resolves to whatever you return instead of requiring that you call resolve function with the value.
Inside an async function, you can await other Promises. This simulates non-asynchronous code, but it is just syntax. It doesn't let you do anything you couldn't do with then(), it just gives you a simpler syntax.
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.