I am trying to understand async/await and understanding the difference of await vs. just calling the function as-is, would be synchronous anyways, right?
function foo() {
this.doSomething(); // waits for this to run before going to next line
return "1";
}
async foo() {
await this.doSomething(); // waits for this to run before going to next line
return "1";
}
aren't they both waiting for doSomething() to finish?
If doSomething() is an async function or return a Promise: then the first example doesn't wait for whatever happens inside doSomething() to complete. doSomething() will still be executed, but outside of foo() execution flow.
If doSomething() is a synchronous function: then both examples don't differ.
More explanation: The concept of async/await revolves around Promise, so to understand async/await you should understand Promise first.
A Promise consist of an asynchronous operation and a future return value of that asynchronous operation.
The async modifier makes a function asynchronous by making it return a Promise. Whenever you call an async function, the content of the function is actually wrapped into a Promise and executed outside of the calling site flow. A plain call of a async function will return a Promise instead of the value of the function.
async function intFunction() {
return 1
}
function foo() {
const result = intFunction(); // result is actually a Promise, not 1.
console.log(result instanceof Promise); // should print true
}
foo();
The await keyword "waits out" a Promise. Whenever you call await with a Promise, the Promise is executed, the result is waited out and returned in the same execution context where you call it. Therefore, it only makes sense to be able to call await in a asynchronous context only, so you won't block the single thread of the JS engine.
async function intFunction() {
return 1
}
async function foo() {
const promise = intFunction();
const value = await promise;
console.log(value === 1); // should be true
}
foo();
// You can call an asynchronous function in the outermost context in running Node.js,
// the engine will wait for all those functions to finish before exiting.