gpt4 book ai didi

node.js - 解决所有 promise 后的返回值

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:11 24 4
gpt4 key购买 nike

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

我尝试实现 async await,但我不确定我必须将它们准确地放在哪里。

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、日期、标题和信息的数组 result。但我得到的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com