Salman Arshad
Salman Arshad

Reputation: 371

Javascript Promise chaining not working as expected

I am trying to return a promise inside a promise but cannot get it to work Here is my code

async function main() {
  return new Promise((resolve, reject) => {
    p = new Promise((resolve, reject) => {
      f2(async() => {
        resolve();
      });
    });
    array = [];
    array.push(p);
    Promise.all(array).then(resolve(1));
  });
}
setTimeout(async() => {
  console.log(await main());
}, 0);

function f2(callback) {
  console.log("h called");
  setTimeout(() => {
    callback();
  }, 4000);
}

I expect that he array will be resolved after the timeout in f2() but it is resolving instantly. Any help will be appreciated

Upvotes: 0

Views: 81

Answers (1)

Stradosphere
Stradosphere

Reputation: 1285

The resolve function is being called right away, try something like this:

Promise.all(array).then(() => {
    resolve(1);
});

Edit: I wanted to add that what is passed to the then() callback of a promise is a statement, using resolve(1) is a call to execute that code, but by wrapping that function call in an anonymous function declaration, the entire function declaration is passed, and then called when needed.

Upvotes: 1

Related Questions