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 !
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);
});
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 await
ing the Promise.all
, you wait for them all to finish/resolve first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With