Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.all returns function

I would like use Async/Await with fetch API. So, i've 2 async function for return result.json().

I add my 2 Promise in Promise.all([]), but the values returned is 'function()'.

My code :

  // Load external users
  const externalUsers = async () => {
    const result = await fetch(url);
    return result.json();
  };

  const localUsers = async () => {
    const result = await Users.allDocs({ include_docs: true });
    return result.rows;
  };

  Promise.all([externalUsers, localUsers]).then(values => {
    console.log(values); // return (2) [function, function]
  });

I don't understand why. Can you help me ?

Thank you community !

like image 296
s-leg3ndz Avatar asked Dec 10 '22 09:12

s-leg3ndz


2 Answers

Run your functions in the Promise.all. So they will return Promises which will be settled and passed to the then function.

Promise.all([externalUsers(), localUsers()]).then(values => {
    console.log(values);
});
like image 121
Suren Srapyan Avatar answered Dec 20 '22 09:12

Suren Srapyan


You should await your Promise.all

const values = await Promise.all([...]);
const value1 = values[0];
...

The reason you are seeing functions, is because Promise.all returns a Promise that resolves to an array. So by awaiting the Promise.all, you wait for them all to finish/resolve first.

like image 33
Matthew Herbst Avatar answered Dec 20 '22 09:12

Matthew Herbst