To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes up to two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function called onFulfilled that’s mean the promise is fulfilled. If the function onRejected is called that means the promise is rejected.
Syntax:
Promise.then(onFulfilled, onRejected)
The below example will illustrate the approach:
Example 1: In this example, we will see the use of Promise with then() block and setTimeout() method.
HTML
<!DOCTYPE html> < html > < head > < title > How to wrap setTimeout in a promise? </ title > </ head > < body > < h1 style = "color:green;" > neveropen </ h1 > < h3 > How to wrap setTimeout in a promise? </ h3 > < br > < button onclick = "change()" > Click to print </ button > < p id = "gfg" ></ p > < script > function change() { return new Promise(function (resolve, reject) { // Setting 2000 ms time setTimeout(resolve, 2000); }).then(function () { document.getElementById("gfg").innerHTML = "Wrapped setTimeout after 2000ms"; }); } </ script > </ body > </ html > |
Output:
Example 2: In this example, we will see the use of Promises with the async function and setTimeOut() method.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> </ head > < body > < h1 style = "color:green;" > neveropen </ h1 > < h3 > How to wrap setTimeout in a promise? </ h3 > < br > < button onclick = "resolvePromise()" > Click to print </ button > < p id = "gfg" ></ p > < script > let gfg = document.getElementById('gfg'); // function for promise example async function resolvePromise() { let newPromise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("Hello Geeks. Wrapped setTimeout() in a promise"); }, 1000); }); let result = await newPromise; gfg.innerHTML = result; } </ script > </ body > </ html > |
Output:
Reference: Promise.prototype.then() Method