In JavaScript, the Promise.race()
method allows you to execute a set of promises and return a new promise that is resolved or rejected as soon as any of the promises in the set is resolved or rejected.
This can be useful when you need to perform multiple asynchronous tasks and you only care about the result of the first task that completes.
Using a generator function with Promise.race()
allows you to execute a set of promises in a sequential and controlled manner. A generator function is a special type of function that can pause and resume its execution at certain points, allowing you to write asynchronous code in a synchronous style.
Here’s how you can use a generator function with Promise.race()
:
function* gen() {
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Result 1");
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Result 2");
}, 2000);
});
const result = yield Promise.race([promise1, promise2]);
console.log(result);
}
const iterator = gen();
iterator.next().value.then((result) => iterator.next(result));
In this example, we define a generator function called "gen()"
that creates two promises, "promise1"
and "promise2"
, with a timeout of 1 second and 2 seconds respectively. We then use Promise.race()
to execute these promises and pause the generator function until one of the promises is resolved or rejected. The result of the winning promise is then assigned to the "result"
variable using the "yield"
keyword.
We create an iterator object for the generator function and call the "next()"
method to start the generator function. This returns a promise that resolves when the first "yield"
statement is encountered. We then attach a ".then()"
method to this promise that calls the "next()"
method again with the result of the promise. This resumes the generator function and passes the result of the winning promise to the "result"
variable. Finally, we log the "result"
variable to the console.
When you run this code, you’ll see that the result of the winning promise is logged to the console after the specified timeout period. In this case, "Result 1"
is logged to the console after 1 second because "promise1"
resolves before "promise2"
.
Using a generator function with Promise.race()
can be useful in a variety of scenarios.
For example, you could use it to implement a timeout for an asynchronous operation.
Here’s an example:
function* gen() {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Result");
}, 5000);
});
const result = yield Promise.race([promise, timeout(2000)]);
console.log(result);
}
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Timeout"));
}, ms);
});
}
const iterator = gen();
iterator
.next()
.value.then((result) => iterator.next(result))
.catch((error) => console.error(error));
In this example, we define a generator function called "gen()"
that creates a promise with a timeout of 5 seconds. We then use Promise.race()
to execute this promise and a custom "timeout()"
function that creates a promise with a timeout of 2 seconds. We pause the generator function until one of the promises is resolved or rejected, and the result of the winning promise is assigned to the "result"
variable.
We also define a "timeout()"
function that returns a promise that rejects with an "Error"
object after the specified timeout period. This allows us to implement a timeout for the asynchronous operation and reject the promise if it takes too long to complete.
We create an iterator object for the generator function and call the "next()"
method to start the generator function. This returns a promise that resolves when the first "yield"
statement is encountered. We then attach a ".then()"
method to this promise that calls the "next()"
method again with the result of the promise. This resumes the generator function and passes the result of the winning promise to the "result"
variable. If the "timeout()"
function is the winning promise, it will reject the promise with an "Error"
object, which we handle with a ".catch()"
method and log the error to the console.
When you run this code, you’ll see that the promise is rejected with an "Error"
object after 2 seconds because the "timeout()"
function wins the Promise.race()
race. This allows you to implement a timeout for an asynchronous operation and handle the timeout gracefully.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.