Home >Web Front-end >JS Tutorial >How Can I Turn `setTimeout` into a Promise in JavaScript?
In this article, we'll explore how to transform setTimeout, a function that executes a callback after a specified delay, into a Promise that can be used to handle asynchronous operations.
Modern JavaScript supports native Promises that provide a convenient way to represent asynchronous operations. To convert setTimeout into a Promise, we can wrap it in a Promise constructor and pass the resolve function as the callback:
function later(delay) { return new Promise((resolve) => { setTimeout(resolve, delay); }); }
This function will return a Promise that resolves after the specified delay.
If you prefer to create your own Promise implementation, you can define a promise prototype and use it as follows:
function setTimeoutReturnPromise() { function promise() { } promise.prototype.then = function() { console.log('timed out'); }; setTimeout(() => { return this; // Return the promise object }, 2000); return new promise(); }
To create a cancellable Promise, we can wrap setTimeout in a custom object that provides a cancel method:
const later = (delay, value) => { let timer = 0; let reject = null; const promise = new Promise((resolve, _reject) => { reject = _reject; timer = setTimeout(resolve, delay, value); }); return { get promise() { return promise; }, cancel() { if (timer) { clearTimeout(timer); timer = 0; reject(); reject = null; } } }; };
This object returns a Promise and a cancel method that can be used to terminate the operation.
The above is the detailed content of How Can I Turn `setTimeout` into a Promise in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!