Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected reserved word "await", node.js is correct version

I am trying to run a function asynchronously 20 times. I have the function definition:

import axios from 'axios';

async function updateUser (url, user) {
        return new Promise((resolve, reject) => {
            axios.put(url, JSON.stringify(user))
                .then(response => {
                //Folio returned code 204
                console.log('The user has been updated');
                resolve(response.data);
                }).catch((err) => {
                //Folio returned error
                console.error(`Error Text: ${err.response.data}`);
                console.error(`Error Code: ${err}`);
                });
        });
    };

  export {updateUser};

Then I am trying to loop through users in an external JSON, and update them to my system 20 at a time:

import {updateUser} from './updateUser.js';
import usersjson from './jsons/users.json';
let promises=[];
if (usersjson.users.length) {
    try {
        for (const user of usersjson.users) {
            update = new promise ((resolve,reject) => {
                updateUser(url, user)
                .then((list) => {resolve(list)})
                .catch((error)=>{reject(error)})
            });
            promises.push(update);
            if (promises.length = 20) {
                await Promise.all(promises)
                    .then((responses)=> {
                      console.log(responses);
                      promises=[];
                    }).catch((err)=> {
                      console.log(err);
                    });
            }
        }
    } catch(err)=> {
        console.log(err);
    }
}

However, I am getting an error message in the console:

await Promise.all(promises)
^^^^^

SyntaxError: Unexpected reserved word

My node version is 12.19.0 (based on previous questions, it seems it has to be at least 10, so that shouldn't be the issue).

When I run the function without await, they work correctly (i.e. the users are updated on my system). It also seems that the for loop is asynchronous by itself, but I'm afraid that if there will be too many calls simultaneously my system will block the API, so I want to make 20-50 calls at a time, tops.

like image 341
Nimrod Yanai Avatar asked Feb 11 '21 15:02

Nimrod Yanai


Video Answer


1 Answers

In order to use await you need to declare the function in which you are putting the await as async

For example:

const functionReturningPromise = (input) => {
  return new Promise((resolve, reject) => {
    if (!input) {
      return reject();
    }
    
    return resolve();
  });
}

const functionAwaitingPromise = async () => {
  for (let i = 0; i < 20; i +=1) {
    try {
      await functionReturningPromise(i);
      
      console.log(i);
    } catch (error) {
      console.log(error);
    }
  }
}
like image 167
mattigrthr Avatar answered Oct 06 '22 02:10

mattigrthr