node.js - 所有 promise 完成后返回值

标签 node.js promise async-await

我正在编写一个nodejs代码,该代码从站点获取数据,解析它,查找特定数据并为之前获取的数据获取其他内容。但最终的返回语句返回时没有从第二个 API 调用中获取的值。

我尝试实现异步等待,但我不确定应该将它们准确地放在哪里。

const getMainData = async val => {
  let result = [];

  //get xml data from the API
  const xmlData = await getSiteContent(`value`); //axios call

  parseString(xmlData, (err, json) => { //convert xml to json

    const { entry } = json.feed; // array of results.
    result = entry.map(report => {
      const secondInfo = getSomeMoreData(report.something); //axios call
      const data = {
        id: report.id,
        date: report.date,
        title: report.title
      };
      data.info = secondInfo;
      return data;
    });

  });


  return { result };
};

我期望函数返回包含 id、日期、标题和信息的数组结果。但我得到的 info 为 null,因为它会转到另一个执行更多 API 调用的函数。

最佳答案

尝试将 parseString 包装在 promise 中,以便您可以等待结果,然后创建 entry.map回调 async 函数,以便您可以使用 await 关键字等待 axios 获取结果。

async function xml2json(xml) {
  return new Promise((resolve, reject) => {
    parseString(xml, function (err, json) {
      if (err)
        reject(err);
      else
        resolve(json);
    });
  });
}

const getMainData = async val => {
  //get xml data from the API
  const xmlData = await getSiteContent(`value`); //axios call

  const json = await xml2json(xmlData);
  const { entry } = json.feed; // array of results

  const result = await Promise.all(
    entry.map(async report => {
      const secondInfo = await getSomeMoreData(report.something); // axios call
      const data = {
        id: report.id,
        date: report.date,
        title: report.title,
      };
      data.info = secondInfo;
      return data;
    })
  )

  return { result };
}

请告诉我这是否有效。如果没有,我可以尝试进一步帮助您。

关于node.js - 所有 promise 完成后返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122710/

相关文章:

javascript - Selenium - send_keys() 发送不完整的字符串

javascript - 从 promise Angular 2内部设置类的全局变量

c# - linq 子句中的值不能为空

node.js - 无法从文件读取并将相同的内容写入nodejs中的另一个文件

node.js - MomentJS:比较不同时区的时间

javascript - Protractor 嵌套 for 循环

javascript - 然后 jquery 并获取 src - 将图像上传到服务器

c# - 是否有必要等待单个异步调用

python - 有什么理由使用 Python 的基于生成器的协程而不是 async/await 吗?

javascript - Node.js 在 Windows 上找不到/usr/bin/helloworld.js