【发布时间】:2018-01-25 23:31:58
【问题描述】:
使用 Express,我正在使用 .map 创建一组 API 调用,我希望将其结果合并到一个响应对象中。由于每次调用都使用不同的查询参数,我想使用查询参数作为响应对象的键。
我使用 axios 创建 GET 请求,它返回一个承诺,然后我使用 axios.all 等待所有承诺解决。
问题是,在 promise 解决后,我不再能够访问用于创建它们的变量。如何将这些变量附加到 Promise 以供以后参考?
这里是 API:
router.get('/api', (req, res) => {
const number = req.query.number;
res.json({ content: "Result for " + number });
});
这是我尝试合并结果的地方:
router.get('/array', async (req, res) => {
res.locals.payload = {};
const arr = [1, 2, 3, 4, 5];
const promises = arr.map(number => {
return axiosInstance.get('/api', { params: { number: number } })
});
const results = await axios.all(promises);
results.map(r => {
// number should match original, but I no longer have
// access to the original variable
number = 1;
res.locals.payload[number] = r.data;
});
res.json(res.locals.payload);
});
/array 上的 GET 结果:
{
"1": {
"content": "Result for 5"
}
}
在创建 Promise 对象以保留密钥时我可以做什么?
【问题讨论】:
-
数组中的索引号does match the original!
标签: javascript express promise