在 node.js 应用程序中,我试图从 API 中查找产品列表,然后仅获取第一项的缩略图。
在我的代码中 getOrderDetails 是一个承诺,然后如果它是第一个产品,它会调用函数 getImage 这也是一个承诺。
但是,当我运行代码时,会在没有缩略图的情况下填充 orderDetails - 所以看起来代码没有等待 getImage 函数解析。
请有人解释我做错了什么吗?
先感谢您!
if (siteConfig.storeIntegration == 'Cart') {
getOrderDetails(restPathOrder)
.then(function(res) {
var orderDetails = '';
for (i = 0; i < res.items.length; i++) {
productId = res.items[i]['productId'];
thumbnail = '';
if (i == 0) {
getImage(productId, restApiKey)
.then(function(res) {
thumbnail = res;
console.log('thumbnail:' + res);
})
}
orderDetails = orderDetails + res.items[i]['quantity'] + ',' + res.items[i]['name'] + ',' + productUrl + ',' + thumbnail;
}
console.log(orderDetails);
})
}
function getOrderDetails(restPath) {
return new Promise((resolve, reject) => {
request(restPath, function (error, response, body) {
if (!error && response.statusCode == 200) {
restData = JSON.parse(body);
resolve(restData)
}
})
})
}
function getImage(productId, restApiKey) {
return new Promise((resolve, reject) => {
var restPathProduct = storeURL + restApiKey + productId;
request(restPathProduct, function (error, response, body) {
if (!error && response.statusCode == 200) {
restData = JSON.parse(body);
thumbnail = restData.image[0];
resolve(thumbnail);
}
})
})
}
我可以建议使用新await
语法吗?
async main() {
if (siteConfig.storeIntegration == 'Cart') {
let res = await getOrderDetails(restPathOrder);
var orderDetails = '';
for (i = 0; i < res.items.length; i++) {
productId = res.items[i]['productId'];
let thumbnail = '';
if (i == 0) {
thumbnail = await getImage(productId, restApiKey);
}
orderDetails += res.items[i]['quantity'] + ',' + res.items[i]['name'] + ',' + productUrl + ',' + thumbnail;
}
console.log(orderDetails);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句