Asynchronous JavaScript
Last updated
Was this helpful?
Last updated
Was this helpful?
When you don't know when the task will return so you can continue on instead of waiting for the task to return. For example, when you make a call to a web API, this is an asynchronous task.
This topic is going to follow the video below closely. He does a great job of explaining the topic.
setTimeout is a JavaScript function that executes a function in the future, based on the number of ms specified.
The following code is calling setTimeout five times, and each call will wait 1, 2, 3, 4, and 5 seconds before it runs the statement.
We're going to use setTimeout to show how callbacks can be used to sequence code.
We have created two function.
getAnimals - prints out the names of the animals in the array after 1 second.
createAnimal - adds an animal to the array after 2 seconds.
When this code is run, the animals are logged to the console before the new one is added.
The old way to sequence these functions would be to use a callback, or to pass the function that is displaying the animals to the function that is updating the animals so that the display function wouldn't be called until after the update function.
In this version, the new animal is added, and then the callback function is called, ensuring that the animal is added before the animals are displayed.
Typically you will only be a consumer of promises, i.e. you will call functions that return a promise, but we'll show here how to create a Promise so that you understand how it works and the expected return values.
ES7 introduced a very convenient way to execute code that returns a promise. There are two new keywords in the JavaScript language.
async - used to identify a function as asynchronous. This is necessary if you are going to use the associated "await" keyword.
await - used to tell the code to wait for the asynchronous call to return before proceeding.