【问题标题】:Node JS with axios async/await: write response to local file带有 axios async/await 的节点 JS:将响应写入本地文件
【发布时间】:2020-11-22 14:32:12
【问题描述】:

我正在开发一个 Node CLI 应用程序以在本地使用。它将 CSV 文件作为输入,并根据其 userId 列中的值,一次使用其中一个值作为输入向 API 发出 GET 请求。我在下面创建了一个虚拟示例。 这是一个 async 函数中的 axios 请求,它返回一个 Promise:

const axios = require("axios");
const utils = require("./utils");
const fs = require("fs").promises;

async function getTitleGivenId(id) {
  try {
    return await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);
  } catch (error) {
    console.error(error);
  }
}

// This works fine
getTitleGivenId(1).then(res => {
  console.log(res.data.title);
});

我想出这个是为了写一个 CSV,但是 allData 字符串在 map 函数中没有得到更新:

async function saveTitles(inCsv, outCsv) {
  try {
    const arrOfObj = utils.readCsv(inCsv);
    // [
    //   { userId: '1', color: 'green' },
    //   { userId: '2', color: 'blue' },
    //   { userId: '3', color: 'red' }
    // ]

    let allData = "color,title\n";
    arrOfObj.map(o => {
      let title;
      getTitleGivenId(o["userId"]).then(res => {
        title = res.data.title;
        allData += `${o["color"]},${title}\n`;
      });
    });
    await fs.writeFile(outCsv, allData);
  } catch (err) {
    console.error(err);
  }
}

// This writes only "color,title" to "outCsv.csv"
saveTitles("./inputCsv.csv", "./outCsv.csv");

任何建议/替代方法将不胜感激。

【问题讨论】:

    标签: javascript node.js async-await axios


    【解决方案1】:

    它会更新。你只是没有等待它完成。 map() 函数已执行,但它不会等待内部的 promise 完成。因此,一种选择是也将 map 函数设为 async,然后等待所有迭代完成:

    let allData = "color,title\n";
    await Promise.all( arrOfObj.map( async (o) => {
      const res = await getTitleGivenId(o["userId"])
      const title = res.data.title;
      allData += `${o["color"]},${title}\n`;
    }) );
    await fs.writeFile(outCsv, allData);
    

    【讨论】:

    • 传奇,谢谢。我整个周末都在为 async/await 苦苦挣扎。
    猜你喜欢
    • 2022-01-22
    • 2018-09-14
    • 2019-12-18
    • 1970-01-01
    • 2020-09-10
    • 2015-08-26
    • 2020-08-19
    • 2016-03-14
    • 2019-03-14
    相关资源
    最近更新 更多