Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asynchronous functions not executing sequentially as it should be

My code is behaving in a weird way. Here is a snippet and its output:

  let files = //files is an array

  Promise.each(files, file => {
    return epub.file(file.name).async('string').then(content => {
        let mmls = //mmls is an array

        Promise.each(mmls, mml => {
          return mj.typeset({math: mml, format: 'MathML', svg: true}).then(mjdata => {
            // do something
          })
        }).then(() => {
          console.log(0)
        })
    })
  }).then(() => {
    console.log(1)
  })

It would log in the console:

0
0
0
0
0
0
0
1
0  // one '0' after '1'

I found it weird how did one last '0' is logged if the '1' is already logged?

FYI: I'm using bluebird.

like image 362
Kyle Oliva Avatar asked Aug 08 '26 22:08

Kyle Oliva


1 Answers

Say both promises take 1 second to execute, if you don't chain your promises correctly:

somePromise.then(() => {
    // 1.
    someOtherPromise.then(() => {
        // 3.
        console.log("inner");
    });
}).then(() => {
    // 2.
    console.log("outer");
});

First, 1. will occur after t+1s. It then triggers someOtherPromise, but doesn't wait for it, so 1. finishes "synchronously", leading to 2. being executed (at t+1s+Ɛns). At t+2s, 3. is executed. If you do wait for the other promise though:

somePromise.then(() => {
    // 1.
    return someOtherPromise.then(() => {
        // 2.
        console.log("inner");
    });
}).then(() => {
    // 3.
    console.log("outer");
});

First, 1. will occur after t+1s. It then triggers someOtherPromise, but it does wait for it: 3. will be called only once the returned promise is resolved. So 2. occurs at t+2s, then 3. occurs at t+2s+Ɛns.

Side note: in the functional world, you usually have .map and .flatMap, but JS Promise's .then mixes both depending on what the callback returned thanks to dynamic typing.

like image 73
sp00m Avatar answered Aug 10 '26 12:08

sp00m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!