cdarwin
cdarwin

Reputation: 4291

"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);

Upvotes: 0

Views: 97

Answers (4)

Rainer Plumer
Rainer Plumer

Reputation: 3753

Prints the dates as requested.

var printDates = () => {
    console.log('first date:', new Date());
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log("Promise executed");
            setTimeout(() => {
                console.log('second date:', new Date());
                resolve('All done');
            }, 2000);
        }, 2000);
    });
}

Upvotes: 0

Shant Marouti
Shant Marouti

Reputation: 1325

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);

Upvotes: 3

TLP
TLP

Reputation: 1288

Wrap the timer in the promise and then run your code after the timer promise has been resolved, like so:

new Promise(resolve=>setTimeout(resolve,1000))
   .then(()=>{
       console.log("Promise executed")
    })

Upvotes: 0

CD..
CD..

Reputation: 74096

You can use a promise for creating a delay function, like:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

delay(1000).
  then(() => console.log(new Date())).
  then(() => console.log("Promise executed"))

Upvotes: 1

Related Questions