Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await Promises.all SyntaxError

According to this article: https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8

It seems like it could be possible to use below syntax:

let [foo, bar] = await Promise.all([getFoo(), getBar()]);

for multiple promises execution. However while using it I get Uncaught SyntaxError: Unexpected identifier.

How can i use async/await and promise.all to achieve multiple simultaneous operations executed and one resolve with a response.

-----EDITED

the function i am using inside promise.all is this one:

async function getJson(callback) {
    try {
        let response = await fetch('URL_LINK_HERE');
        let json = await response.json();
        return json;
    } catch(e) {
        console.log('Error!', e);
    }
}

as a test field i am using google chrome Version 60.0.3112.113

like image 322
Mevia Avatar asked Nov 16 '25 20:11

Mevia


1 Answers

Most likely your code looks something like this:

var thingsDone = await Promise.all([
  Promise.resolve("eat"),
  Promise.resolve("sleep")
]);
console.log(thingsDone);

This will not work because the await keyword is only valid within an async function (which the global context is not). It will simply cause a syntax error.

One way to handle this is to use it like a regular old promise and not using the await keyword:

Promise.all([
  Promise.resolve("eat"),
  Promise.resolve("sleep")
]).then((thingsDone) => console.log(thingsDone));

Or if you want to get fancy (or need more room to write an expressive function), wrap your logic in an async function and then handle it like a promise:

async function doThings() {
  var eat = await Promise.resolve("eat");
  var sleep = await Promise.resolve("sleep");
  return Promise.all([Promise.resolve(eat), Promise.resolve(sleep)]);
}

doThings().then((thingsDone) => console.log(thingsDone));

This would allow you to use await as needed and is much more helpful in a more complicated function.

Or even more succinctly using an immediately-executing async function:

(async() => {
  var eat = await Promise.resolve("eat");
  var sleep = await Promise.resolve("sleep");
  return Promise.all([Promise.resolve(eat), Promise.resolve(sleep)]);
})().then((thingsDone) => console.log(thingsDone));
like image 118
Steven Goodman Avatar answered Nov 18 '25 10:11

Steven Goodman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!