简体   繁体   English

我无法使用 nodejs 在 for 循环中调用 API

[英]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:我正在尝试使用Nodejs在for循环内调用API,当代码执行时,API仅调用最后一个元素:代码:

      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?当此代码仅执行由 API 执行的数组中的最后一个元素时,我正在寻找的是为 for 循环的每次迭代执行 api,有什么帮助吗?

Not sure how your full function looks like, but you should build your function as fully structured as async-await.不确定您的完整 function 的外观如何,但您应该将 function 构建为完全结构化的异步等待。

And also you could use map function instead of for .你也可以使用map function 代替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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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