I am learning about Javascript ES2017 async/await feature. Been reading a lot about it, and came across an understanding that await is like yield, and allows us to wait for the
await
tells the runtime to wait for the promise returned from the expression on the right-hand side to be fulfilled.
In the following code control is stopped in the async function until the promise returned by the fetch
invocation is fulfilled, and the response value sent to the fulfilled promise is printed to the console.
async function go() {
let response = await fetch('http://www.example.com');
console.log(response); // print the response after some time
}
go();
If the await keyword was omitted then control would immediately continue to the next line of the function and the the promise returned by fetch would be immediately printed to the console.
async function go() {
let response = fetch('http://www.example.com');
console.log(response); // print the promise from fetch immediately
}
go();
await
is a contextual keyword that only means something special when used inside a function marked async
. By marking a function async
you are telling the runtime to:
yield
a value where the user types await
(usually a promise)In this way, asynchronous control flows can be written in a style closer to the traditional synchronous style. ie. without nesting, callbacks or visible promises. try..catch
can also be used in the normal way.
As another answer mentions, async
, and await
are syntactic sugar that ask the runtime to use existing objects (generator functions and Promises) behind the scenes to make async code easier to read and write.
can you await every line
I would guess you can. If the expression on the right of the await
results in a promise, then the async/await behaviour detailed above occurs.
If the expression on the right of the await
does not result in a promise, then I would guess the value is wrapped in a resolved promise for you, and logic continues per the above, as though the value came from an immediately resolved promise. This is a guess.