0

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Salman Arshad
  • 343
  • 6
  • 23
  • 2
    `.then(resolve(1));` <= is not a callback. It's immediately executing – Taplar Apr 16 '20 at 17:07
  • 1
    Does this answer your question? [Why does click event handler fire immediately upon page load?](https://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load) – Taplar Apr 16 '20 at 17:07
  • Duplicate covers the same issue, but related to event handlers – Taplar Apr 16 '20 at 17:07

1 Answers1

1

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.

Stradosphere
  • 1,285
  • 3
  • 14
  • 40