Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

asynchronous - JavaScript - .then() chain not queued up

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...