1

I'm trying to resolve the promise in the getABC function, but the local const variable b returns undefined. How do I implement the callback function used by the getB function so that it returns the destructured array item with the value of 'B'.

const [A, B, C] = ['A', 'B', 'C'];

function getA() {
  return A;
}

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

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

function getABC() {
  return new Promise((resolve, reject) => {
    const a = getA();
    const b = getB(b => b);
    const c = getC().then(item => item).catch(err => console.log(err));

    resolve([a, b, c])
  });
}

getABC().then((arr) => console.log(arr));
Moon Shine
  • 29
  • 5
  • Your `getB` doesn't return anything. You just give it a callback that essentially does nothing. It just gets called 10 milliseconds later. Was it meant to actually resolve a promise 10ms later? – VLAZ Jan 03 '22 at 18:48
  • getB is meant to return global variable B. – Moon Shine Jan 03 '22 at 18:52
  • 2
    `function getABC() { return Promise.all([getA(), new Promise(getB), getC()]); }` But really you should just change the implementation of `getB` to return a promise instead of accepting a callback. – Bergi Jan 03 '22 at 18:56
  • The code is for a coding challenge, so I didn't write it. – Moon Shine Jan 03 '22 at 19:04
  • 1
    @MoonShine - "_I'm trying to resolve the promise in_" & "_How do I implement the callback function_" - it _appears like_ you wrote it based on your question - regardless, Bergi answered the question you wrote very directly. – Randy Casburn Jan 03 '22 at 19:12
  • @MoonShine that's not at all what it does. – VLAZ Jan 03 '22 at 19:26
  • it does now! thanks, guys. – Moon Shine Jan 03 '22 at 23:40

1 Answers1

1

You also have to wrap setTimeout inside a Promise, and call Promise.all before resolve:

const [A, B, C] = ['A', 'B', 'C'];

function getA() {
  return A;
}

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

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

function getABC() {
  return new Promise((resolve, reject) => {
    const a = getA();
    const b = getB(b => b);
    const c = getC().then(item => item).catch(err => console.log(err));

    resolve(Promise.all([a, b, c]));
  });
}

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

All of these can truly be simplified if you use async/await.

konsolebox
  • 72,135
  • 12
  • 99
  • 105