【问题标题】:Multiple API result in one array/object using node js多个 API 使用节点 js 生成一个数组/对象
【发布时间】:2020-08-31 23:05:14
【问题描述】:

我想在每一行谷歌表格上调用一个 API。 API 将在所有行完成后返回我想要推送到数组中的 JSON 对象。我想对这个数组做进一步的处理。

例如 resultArr = [ {first Api result}, {second api result} .... so on]

下面是我的代码,我试试看

const axios = require("axios");
const assert = require("assert");
const path = require("path");
const fs = require("fs");
const { GoogleSpreadsheet } = require("google-spreadsheet");

const doc = new GoogleSpreadsheet("ABCDEFGHIJKLMOPQRSTUVWxyz");
doc.useApiKey("ABCDEFGHIJKLMOPQRSTUVWxyz");

let jsonRowArr = ["initial"];

async function test1() {
    await doc.loadInfo();

    const sheet = doc.sheetsByIndex[0]; /* or use doc.sheetsById[id] */

    /* read all rows */
    const rows = await sheet.getRows(); // can pass in { limit, offset }

    rows.forEach(async (row, index) => {
        let heading = row["_sheet"]["headerValues"];
        fieldValue = {};
        let rowValue = row["_rawData"];
        heading.forEach((key, i) => {
            fieldValue[key] = rowValue[i];
        });

        //start here
        let APIParam = {
            test_name: `test ${index}`,
            shipping_method: {
                before_decimal_point: fieldValue["Before Decimal"],
                after_decimal_point: fieldValue["After Decimal"],
                closest_round: "100",
            },
            shipping_price: fieldValue["3 Digit"],
            method_name: "get_shipping_after_round",
            expected_rate_up: ["Expected Down 3"],
            expected_rate_down: ["Expected Up"],
        };

        APIAfterApiData = await apiCallNewFn(APIParam);

        await jsonRowArr.push("dsv");
        await jsonRowArr.push(APIAfterApiData);
    });
    return await jsonRowArr;
}
apiCallNewFn = async (params) => {
    let { data } = await axios.post(
        "http://api.example.com/call_function.php",
        null,
        {
            params,
        }
    );
    // console.log('data...', data);
    data["test_name"] = await params.test_name;
    data["expected_rate_up"] = await params.expected_rate_up;
    data["expected_rate_down"] = await params.expected_rate_down;

    return await data;
};

(async () => {
    let customTestObj = await test1();
    console.log("I want fianl result here");
    console.log(customTestObj);
    console.log("for further process");
})();

【问题讨论】:

    标签: node.js api asynchronous async-await es6-promise


    【解决方案1】:

    这个修改怎么样?在这个修改中,我使用了 apiCallNewFn 返回 Promise。并且使用 for 循环代替 forEach。 Ref当你的脚本被修改后,变成如下。本次修改,修改了test1()apiCallNewFn

    test1():

    async function test1() {
      await doc.loadInfo();
      const sheet = doc.sheetsByIndex[0];
      const rows = await sheet.getRows();
      for (let index = 0; index < rows.length; index++) {
        const row = rows[index];
        let heading = row["_sheet"]["headerValues"];
        fieldValue = {};
        let rowValue = row["_rawData"];
        heading.forEach((key, i) => {
          fieldValue[key] = rowValue[i];
        });
        let APIParam = {
          test_name: `test ${index}`,
          shipping_method: {
            before_decimal_point: fieldValue["Before Decimal"],
            after_decimal_point: fieldValue["After Decimal"],
            closest_round: "100",
          },
          shipping_price: fieldValue["3 Digit"],
          method_name: "get_shipping_after_round",
          expected_rate_up: ["Expected Down 3"],
          expected_rate_down: ["Expected Up"],
        };
        APIAfterApiData = await apiCallNewFn(APIParam);
        jsonRowArr.push("dsv");
        jsonRowArr.push(APIAfterApiData);
      }
      return jsonRowArr;
    }
    

    apiCallNewFn():

    const apiCallNewFn = async (params) => {
      return axios
        .post(
          "http://api.example.com/call_function.php",
          null,
          {
            params,
          }
        )
        .then((res) => {
          let data = { res: res.data };
          data["test_name"] = params.test_name;
          data["expected_rate_up"] = params.expected_rate_up;
          data["expected_rate_down"] = params.expected_rate_down;
          return data;
        });
    };
    

    const apiCallNewFn = async (params) => {
      return axios
        .post(
          "http://api.example.com/call_function.php",
          null,
          {
            params,
          }
        )
        .then((data) => {
          data["test_name"] = params.test_name;
          data["expected_rate_up"] = params.expected_rate_up;
          data["expected_rate_down"] = params.expected_rate_down;
          return data;
        });
    };
    

    注意:

    • 关于apiCallNewFn,请修改脚本以获得您期望的结果。

    【讨论】:

    • 感谢您的宝贵时间让我先检查
    • @Sachin Sarola 感谢您的回复。如果我误解了您的问题并且这不是您期望的方向,我深表歉意。
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多