1

I have a 3 function:

First just returns the value

Second calls a setTimeout

Third returns promise with the value

I can't touch these 3 functions.

Here they are:

const A = "A";
const B = "B";
const C = "C";

function getA() {
  return A;
}

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

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

I need to create a function which will return the output of all three function in the array with promise.

So far I tried this:

function getABC() {
  return new Promise((resolve, reject) => {
    let a = getA();
    let b = getB(B => B);
    let c = getC().then(() => C);
    let arr = [a, b, c];
    resolve(arr);
  }).then((arr) => arr);
}

getABC().then((arr) => console.log(arr));

It should return ['A', 'B', 'C'] but instead it returns ['A', undefined, Promise {<pending>}];

I tried different approaches but they were all false.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

2 Answers2

2

Simplest way seems to be add this to the original code, as suggested by @rksh1997 above

Promise.all([
    getA(),
    new Promise(getB), // callback == 'resolve()'
    getC(),
]).then(console.log);
RoyM
  • 1,118
  • 1
  • 9
  • 28
0

Here is a way of doing it:

const A = "A";
const B = "B";
const C = "C";

function getA() {
  return A;
}

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

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

function getABC() {
  // This is used to extract the value from the function getB
  const obj = {};
  const cb = (b) => obj.b = b;
 
  getB(cb);
  // The callback cb will be called only in 10ms, that why there is a
  // timeout here to wait that the value b is extracted
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(getC().then(c => [getA(), obj.b, c])), 10);
  });
}

// Another way: wrap the function getB and then use Promise.all
function getABC2() {
  function wrapGetB() {
    const obj = {};
    const cb = (b) => obj.b = b;
    getB(cb);
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(obj.b), 10);
    });
  }

  return Promise.all([getA(), wrapGetB(), getC()]);
}

getABC().then((arr) => console.log(arr));
getABC2().then(console.log);
Mickael B.
  • 4,755
  • 4
  • 24
  • 48