我在返回创建的对象时遇到问题,代码如下:
Within the Promise。allsettle,我最终得到了我循环的结果,并将每个数组推到一个对象(这创建了对象fine),当我尝试返回该对象时,它是空的。
我想是因为我的承诺还没有兑现,我试过了:
Promise.resolve(returnedData)然后返回它,甚至。then(results =>结果).
我错过了什么?我想我已经看了太久了,我好像错过了什么。
const getProductData = () => {
debugger;
const productIds = [];
const returnedData = [];
const customerLocation = getCustomerLocation();
productdataItems.forEach((product) => {
productIds.push(
product
.querySelector('[data-test-id="product-card-code"]')
.innerHTML.replace(/[^0-9]/g, ''),
);
});
const items = productIds.map((product) => ({
productCode: product,
quantity: 1,
}));
// Load in products for other steps
const promises = [];
productIds.forEach((sku) => {
promises.push(getProduct(sku));
});
Promise.allSettled(promises).then((results) => {
// Stock requires location data.
if (customerLocation) {
getEligibility(items, customerLocation).then((eligibility) => {
getStock([customerLocation.collectionBranchId], productIds).then(
(stock) => {
results.forEach((result, i) => {
if (result.value.product) {
returnedData.push({
Product: result.value.product,
Eligibility: eligibility[i],
Stock: stock[i].quantity,
ProductMarkup: productdataItems,
PostCode: customerLocation.deliveryPostcode,
});
}
});
},
);
});
}
});
return returnedData;
};
返回数据在promise. allsettle之外。所以它在Promise之前被返回。allsettle已完成,因此为空。
你应该做的是把returnData的返回值移到Promises
return Promise.allSettled(promises).then((results) => {
... ...
return returnData;
}
getProductData需要是一个返回承诺结果的异步方法。