Sometimes, we want to make a promise from setTimeout with JavaScript.
In this article, we’ll look at how to make a promise from setTimeout with JavaScript.
How to make a promise from setTimeout with JavaScript?
To make a promise from setTimeout with JavaScript, we can use the Promise constructor.
For instance, we write
const later = (delay) => {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
};
to create the later function which returns a promise we create with the Promise constructor.
We create the promise by calling Promise with a callback that calls setTimeout with resolve as its callback.
The delay is in milliseconds.
The promise will resolve after delay milliseconds as a result.
Conclusion
To make a promise from setTimeout with JavaScript, we can use the Promise constructor.