0

I'm trying to call an API inside a for loop using Nodejs,when the code is executed only the last element is called by the API: the code :

      var array=[12,124,852,256,5677,256,5679,2546,567,28,574]
      for(var i=0;i<array.length;i=i++){
         var b = array.splice(i,3);        
          const parameters1 = {
            Ids: b.toString(),
            limit: 45,
          }

          const get_request_args1 = querystring.stringify(parameters1);

          const options1 = {

            method: 'GET',

            host: "host",

            port: '443',

            path: path + '?' + get_request_args1,

            headers: {

                'Accept': 'application/json',

                'authorization': `Bearer ${token}`,

                'Accept-Encoding': 'identity',
                    }

            }

    var req = http.request(options1, (res) => {

        context.log("API CALL...",i);

    var body = "";

    var pages = 0;

    var offset = [];

    var limit = 100000;

    res.on("data", (chunk) => {

        body += chunk;

    });
    res.on("end", () => {
        const obj = JSON.parse(body);
        //context.log('total pages 3 :', pages);
        context.log('total  :', obj.total);
        context.res = { body: offset };
        context.done();

    });

}).on("error", (error) => {

    context.log('ERROR :', error);

    context.res = {

        status: 500,

        body: error

    };
    context.done();
});      

}

when this code is executed only the last element in the array executed by the API, what I'm looking for is executing the api for each iteration of the for loop, any helps please ?

1 Answer 1

0

Not sure how your full function looks like, but you should build your function as fully structured as async-await.

And also you could use map function instead of for.

const yourFunction = async () => {
  try {
    const array = [12,124,852,256,5677,256,5679,2546,567,28,574];

    const requests = array.map(async (item) => {
      ...
      var req = await http.request(async options1, (res) => {

        context.log("API CALL...",i);
      ...
    });

    await Promise.all(requests);
    ...
  } catch (err) {
    console.error(err);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.