Search code examples
javascriptes6-promise

"Starting a promise" when I want to


I want to start some work after an amount of time, and I want this work to return its value through a Promise.

Unfortunately, the body of a promise is immediately executed when you build the promise.

So, the following code prints "Promise executed" and then the two dates. I want the code to print the first date, then "Promise executed", then the last date.

What approach should I follow ?

JS Code :

let p = new Promise(function(resolve) {
    console.log("Promise executed");
    resolve(1);
});
		
		
setTimeout(function() {
    console.log(new Date());
    p.then(function() { 
        console.log("All done"); 
        console.log(new Date());
    });
}, 1000);


Solution

  • You can delay the creation of the promise by wrapping it into a function

    function doWork() {
        return new Promise(function(resolve) {
            console.log('Promise executed');
            resolve(1);
        });
    }
    
    setTimeout(function() {
        console.log(new Date());
        doWork().then(function() {
            console.log('All done');
            console.log(new Date());
        });
    }, 1000);