When you call a function which returns a Promise, it means you are making a call to an asynchronous function.
You can handle the response of an asynchronous function by using either a “then and catch blocks” or by using await.
Sometimes, asynchronous calls can take forever to send the response. It might be because of network failure or the database could be down etc. In such cases, you do not want to wait for the response for ever. You can implement timeout and return an appropriate error message to the caller thus preventing the caller from waiting for ever.
So, there are two cases that you shoud consider.
First case is the regular case. That is, when the operation is completed normally without any problem.
Second case is the exceptional case. That is, when the operation is taking more than the maximum expected time.
In the first case, you should call resolve and return the regular response.
In the second case, you should call reject and return the error message saying that the operation has timed out.
To illustrate this implementation, I will show you two examples:
The following is an example, where the resolve will be called first. This is the regular case
getName = (maxTimeout = 5000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject({
message: `${maxTimeout} ms timed out. Could not process the request within ${maxTimeout} ms`,
});
}, maxTimeout);
setTimeout(() => resolve({ name: “Venkat Ram Taddi” }), maxTimeout – 1000);
});
};
The following is an example, where the reject is called first. This is the exceptional case:
getName = (maxTimeout = 5000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject({
message: `${maxTimeout} ms timed out. Could not process the request within ${maxTimeout} ms`,
});
}, maxTimeout);
setTimeout(() => resolve({ name: “Venkat Ram Taddi” }), maxTimeout + 1000);
});
};
The following code is the caller of asynchronous function:
getName()
.then((response) => {
console.log(response.name);
})
.catch((error) => {
console.log(error.message);
});
Observe that passing maxTimeout while calling the asynchronous function is optional