多个 API 使用节点 js 生成一个数组/对象

Posted

技术标签:

【中文标题】多个 API 使用节点 js 生成一个数组/对象【英文标题】:Multiple API result in one array/object using node 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");
)();

【问题讨论】:

【参考方案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 感谢您的回复。如果我误解了您的问题并且这不是您期望的方向,我深表歉意。

以上是关于多个 API 使用节点 js 生成一个数组/对象的主要内容,如果未能解决你的问题,请参考以下文章

如何使用node.js request()循环数组

循环遍历多维数组以生成新数据并在节点 js / javascript 中追加新的键值

js 生成树形结构数据

节点js停止处理来自角度的多个api请求并在重新启动节点应用程序后工作

映射一个二维数组数组以生成leaflet.js标记

为节点 js 应用程序中的用户生成唯一的 api 密钥以访问您的 api