我正在编写一个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/