【发布时间】:2020-06-07 02:09:57
【问题描述】:
我正在使用 request-promise npm 包在 nodeJS 中进行多个 api 调用。为了让我获得所需的数据,我必须遍历所有类别,然后在每个类别中循环遍历产品数组以获取产品信息。示例类别响应如下
{
"success": true,
"response": [
{
"category_id": 9,
"name": "Leather Wheeled luggage",
"products": [
"TL141911",
"TL141888"
],
"parent_category_id": 34
},
{
"category_id": 10,
"name": "Leather Luggage Weekender Duffles bags",
"products": [
"TL141794",
"TL141658"
],
"parent_category_id": 34
}
}
因为我必须循环并进行 api 调用,我正在尝试使用 Promise.all,但它没有产生正确的结果,它给我一个 404 not found 错误,有人可以帮我看看我在哪里这里出错了?以下是我尝试过的
const rp = require('request-promise');
const requestUrl = "https://stage.tuscanyleather.it/api/v1/";
const categoryRequestUrl = requestUrl + 'categories';
let tuscanApiOptions = {
uri: categoryRequestUrl,
headers: {
'Authorization': 'Bearer asd343'
},
method: 'Get',
json: true
};
rp(tuscanApiOptions)
.then((categResponse) => {
//res.end(categResponse);
let ps = [];
categResponse.response.forEach((category) => {
if (category.products !== undefined) {
category.products.forEach((product) =>{
let productApiOptions = {
uri: requestUrl + `product-info?code=${product}`,
headers: {
'Authorization': 'Bearer asd343'
},
method: 'Get',
json: true
};
ps.push(rp(productApiOptions));
});
Promise.all(ps)
.then((values) => {
console.log(values); //This is where things are going wrong
})
.catch((err) =>{
console.log(JSON.stringify(err,null,2));
})
}
})
})
.catch((error) => {
console.log(error);
//res.status(error.statusCode).send(error.error.error_description);
});
【问题讨论】:
-
一小时前与您的其他问题相关:stackoverflow.com/questions/60358803/…
-
我想,我没有正确地提出问题,所以我认为最好再发布一个包含更多信息的问题
-
你不应该有两个关于同一个基本主题的问题。当人们已经处理了您的问题并正在与您合作时,如果您想澄清问题,请使用“编辑”链接修改您的问题,而不仅仅是打开一个新问题。请删除这两个问题之一。
-
@jfriend00 我已经删除了另一个问题,谢谢
-
代码中显示的
request变量是request-promise模块吗?如果是这样,请将其添加到您的代码中,以便显示。当我使用request-promise模块(顺便说一句已弃用)时,我将其命名为不同的名称,例如rp,因此阅读我的代码的任何人都不会认为它是常规的request模块。
标签: javascript node.js api asynchronous promise