JavaScript - .then() chain not queued up

Viewed 28

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

This is the output

// calling fn #1
// Resolved after 2000 second delay
// calling fn #2
// calling fn #3
// Resolved after 2000 second delay
// Resolved after 2000 second delay
2 Answers

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.

You can try using 'await' this should work

await fn(2000);
Related