【问题标题】:I cannot call an API inside for loop using nodejs我无法使用 nodejs 在 for 循环中调用 API
【发布时间】:2021-11-24 03:07:52
【问题描述】:

我正在尝试使用 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();
});      

}

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

【问题讨论】:

    标签: javascript node.js async-await


    【解决方案1】:

    不确定你的完整函数是什么样的,但你应该构建你的函数,就像 async-await 一样完全结构化。

    您也可以使用map 函数代替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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2021-06-15
      • 2020-05-03
      • 2021-05-18
      相关资源
      最近更新 更多