Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Javascript Promises chain with setTimeout calls not behave as expected

I have the following code to test asynchronous exectution in Javascript, using promises and timeout's:

'use strict'
const { promisify } = require('util')

const print = (err, contents) => { 
  if (err) console.error(err)
  else console.log(contents) 
}

const opA = (cb) => {
  setTimeout(() => {
    cb(null, 'A')
  }, 500)
}

const opB = (cb) => {
  setTimeout(() => {
    cb(null, 'B')
  }, 250)
}

const opC = (cb) => {
  setTimeout(() => {
    cb(null, 'C')
  }, 125)
}

const opAProm = promisify(opA)
const opBProm = promisify(opB)
const opCProm = promisify(opC)

opAProm(print).then((res) => opBProm(print).then((res) => opCProm(print)))

The result I would expect is this:

A
B
C

But instead it gets printed just this:

A

I have looked for a solution and the most similar one I have found is this one although it hasn't help me really: Javascript Promises: then()'s aren't synchronous

So I would like to know how can I solve this, using promises or async/await. Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

After promisifying something, you shouldn't be passing it a callback - rather, only call .then on the resulting Promise. If you remove the prints from the lines like these:

opAProm(print)

and instead chain off the Promise directly, it'll work as desired.

opAProm().then((resultA) => {
    print(resultA);
    opBProm().then((resultB) => {
        print(resultB);
        opCProm()
            .then((resultC) => {
                print(resultC);
            });
    })
});

Or, a better approach:

opAProm()
    .then((resultA) => {
        print(resultA);
        return opBProm();
    }).then((resultB) => {
        print(resultB);
        return opCProm();
    })
    .then((resultC) => {
        print(resultC);
    });

(or use async/await)

Otherwise, if you do (like in your original code)

opAProm(print)

Then the cb is inferred to be the function passed - the cb for opA - which is not connected to the Promise, so further chaining doesn't work. With util's promisify, the callback that the promise replaces should be the final argument of the original function - if you pass it another argument in combination, it'll get out of whack. Unless you change the original functions to accept two arguments, which would be really weird, but would "work".

const opA = (cb, finalcb) => {
    setTimeout(() => {
        cb(null, 'A')
        finalcb();
    }, 500)
}

const opB = (cb, finalcb) => {
    setTimeout(() => {
        cb(null, 'B')
        finalcb();
    }, 250)
}

const opC = (cb, finalcb) => {
    setTimeout(() => {
        cb(null, 'C')
        finalcb();
    }, 125)
}

const opAProm = promisify(opA)
const opBProm = promisify(opB)
const opCProm = promisify(opC)

opAProm(print)
    .then(() => {
        return opBProm(print);
    }).then(() => {
        return opCProm(print);
    });
about 4 years ago · Juan Pablo Isaza Report

0

Promisify removes the last callback function. Meaning, passed print method is useless here. Instead of that, you will get the result in the then/resolve function and print. As @CertainPerformance mentioned, You can either convert to use promise with print in then or use async-await to simplify.

const { promisify } = require("util");

const print = (err, contents) => {
  if (err) console.error(err);
  else console.log(contents);
};

const opA = (cb) => {
  setTimeout(() => {
    cb(null, "A");
  }, 500);
};

const opB = (cb) => {
  setTimeout(() => {
    cb(null, "B");
  }, 250);
};

const opC = (cb) => {
  setTimeout(() => {
    cb(null, "C");
  }, 125);
};

const opAProm = promisify(opA);
const opBProm = promisify(opB);
const opCProm = promisify(opC);

async function main() {
  const resA = await opAProm();
  console.log(resA);
  const resB = await opBProm();
  console.log(resB);
  const resC = await opCProm();
  console.log(resC);
}
main();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!