Skip to content
Advertisement

Return Promise by Aggregating function calls by synchronous, callback driven using setTimeout, promise based

How to pass a callback that waits for the setTimeout to finish and return a promise.

Is there any tweak that can be done here to fix this, when a callback is passed from the function which makes the function to resolve after setTimeout

Or call getB before promise.all() and keep the result ready etc

function getA() {
  return "A";
}
function getB(callback) {
  setTimeout(() => {
    callback("B");
  }, 10);
}

function getC() {
  return Promise.resolve().then(() => "C");
}

function getABC() {
  //need to work here only
  const cb = (val) => val;
  return Promise.all([getA(), getB(cb), getC()]);
}

getABC().then((arr) => console.log(arr));
// expected output [ 'A', 'B', 'C' ]

The expected output is [ 'A', 'B', 'C' ] but receiving [ 'A', undefined, 'C' ] what changes should I make here?

Advertisement

Answer

Update in response to your comment:

TS Playground

function getA () {
  return "A";
}

function getB (callback) {
  setTimeout(() => {
    callback("B");
  }, 10);
}

function getC () {
  return Promise.resolve().then(() => "C");
}

function getABC () {
  const waitForCallback = (invoker) => new Promise(resolve => invoker(resolve));
  return Promise.all([getA(), waitForCallback(getB), getC()]);
}

getABC().then(console.log);

Original answer:

Return a promise from getB:

TS Playground

function getA () {
  return "A";
}

function getB (callback) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(callback("B"));
    }, 10);
  });
}

function getC () {
  return Promise.resolve("C");
}

function getABC () {
  const cb = (val) => val;
  return Promise.all([getA(), getB(cb), getC()]);
}

getABC().then(console.log.bind(console));
Advertisement