15

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.

Nimrod Yanai
  • 777
  • 2
  • 8
  • 30
  • 1
    Does this answer your question? [await is only valid in async function](https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function) – Naren Feb 11 '21 at 16:06
  • Not sure where you get "at least 10" when a quick Google search says it was introduced in node 7.6 and was definitely supported by 8.x ... – Michael Aug 01 '22 at 18:54

1 Answers1

12

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);
    }
  }
}
emjeexyz
  • 376
  • 3
  • 6
  • What do you mean? How do I do that in this case? – Nimrod Yanai Feb 11 '21 at 16:02
  • I just added an abstract example. If you directly run your index.js you can also declare an init function. E.g. const init = async () => {}; and then call init() – emjeexyz Feb 11 '21 at 16:05
  • Ok so... the error I am getting has an async on the function, and it's also inside the `tedious` library, so I'm puzzled. Also, it has no problems with async/await in *my own code*... – Michael Aug 01 '22 at 18:54
  • @Michael can you post a code snippet and the error stack trace? My guess would be that either the library or the node version you are using doesn’t support async/await yet. If that’s the case you would need to use callbacks (`then` and `catch`) for handling asynchronous calls. – emjeexyz Aug 02 '22 at 20:39