We may need to do some processing that takes some time (like retrieving data from a remote server). In this case we might want to wait for the processing to finish before proceeding with the rest of the code.
There are several methods to achieve this, such as promises, async and await.
Promises
This is the first function, meaning the function we want to wait until it finishes before continuing.
function firstFunction(category) {
return new Promise((resolve, reject) => {
// Long processing goes here...
if (category === 'example') {
// Success response.
resolve('success');
} else {
// Handling errors.
reject('error');
}
});
}
We can also return an empty response (e.g. in case there is no result):
function firstFunction(category) {
return new Promise((resolve) => {
// Long processing goes here...
if (category !=== null) {
resolve('success');
}
// Nothing found.
resolve('');
})
}
A promise object can be returned immediately using this shorten syntax (instead of the full return new Promise
syntax):
function firstFunction(category) {
return Promise.resolve('success');
}
Note: fetch
already returns a promise object so we can just return it directly:
function firstFunction() {
return fetch('https://example.com', {
method: 'POST',
}).then((response) => response.text());
}
The function in the example above fetches a text (string) response from a remote URL and returns it as a promise object.
Promise chain
Now we are ready to call firstFunction
and wait for its response.
This can be done by creating a promise chain using then
:
firstFunction().then((response) => {
// At this point "response" is ready and contains the firstFunction response.
if (response === 'success') {
// Do this...
}
});
Async Await
Another way to do this is to use async
and await
:
async function secondFunction() {
const response = await firstFunction();
// The code below the await will not execute until firstFunction is complete.
// At this point "response" is ready and contains the firstFunction response.
if (response === 'success') {
// Do this...
}
}
secondFunction();