简体   繁体   中英

I cannot call an API inside for loop using nodejs

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?

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM