Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Theoretical example regarding .then() syntax...

Why doesn't it wait for the second call to resolve before calling the third?

// Waits ms milliseconds then resolves
const fn = (ms) => {
    return new Promise((res, rej) => {
        setTimeout(()=>res(console.log(`Resolved after ${ms} ms delay`)), ms);
    });
}

console.log(`calling fn #1`);
fn(2000).then(()=>{
    console.log(`calling fn #2`);
    fn(2000);
}).then(()=>{
    console.log(`calling fn #3`);
    fn(2000);
});
question from:https://stackoverflow.com/questions/65853813/javascript-then-chain-not-queued-up

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
962 views
Welcome To Ask or Share your Answers For Others

1 Answer

In order to chain you must return a promise or else it's presumed to be something that's not relevant to the chain:

console.log(`calling fn #1`);
fn1(2000).then(()=>{
    console.log(`calling fn #2`);
    return fn(2000);
}).then(()=>{
    console.log(`calling fn #3`);
    return fn(2000);
});

Also if you want the await form it looks like this:

async function example() {
  console.log(`calling fn #1`);
  await fn1(2000);

  console.log(`calling fn #2`);
  await fn(2000);

  console.log(`calling fn #3`);
  await fn(2000);
};

Which honestly is a lot cleaner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...