简体   繁体   中英

JavaScript Promises with setTimeout resolve in sequence

I want to print 3 messages in a timed sequence, where each message is displayed after n seconds after the previous message is displayed. Requiring to implement this with JavaScript and using Promises, I wrote a function called printLater that returns a Promise that leverages setTimeout to implement the blocking/waiting mechanism as follows:

let printLater = (message, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(message);
            resolve();
        }, delay);        
    })
}

Then, I tried using 3 promises to print the messages in sequence and using delays.

printLater('first message, after 2 seconds from start of program', 2_000)
    .then(printLater('second message, after 5 seconds after first message is displayed', 5_000))
    .then(printLater('third message, after 1 second after second message is displayed', 1_000));

The required output is:

first message, after 2 seconds from start of program
second message, after 5 seconds after first message is displayed
third message, after 1 second after second message is displayed

But the actual output was:

third message, after 1 second after second message is displayed
first message, after 2 seconds from start of program
second message, after 5 seconds after first message is displayed

I am trying to understand why the sequence is out of order, given that I am resolving within the function specified for the setTimeout .

You can create another function to return a wrapper for printLater() :

const printLaterCallback = (message, delay) =>
    () => printLater(message, delay);

Then you can use that in the .then() calls:

printLater('first message, after 2 seconds from start of program', 2_000)
    .then(printLaterCallback('second message, after 5 seconds after first message is displayed', 5_000))
    .then(printLaterCallback('third message, after 1 second after second message is displayed', 1_000));

Hi the Promise chaining is in-correct

const printLater = (message, delay) => new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(`*** ${message} ***`);
    resolve();
  }, delay);
});

printLater('first message, after 2 seconds from start of program', 2000)
  .then((data) => {
    printLater('second message, after 5 seconds after first message is displayed', 5000)
      .then((data) => {
        printLater('third message, after 1 second after second message is displayed', 1000).then((data) => {});
      });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM