这是我的代码:
exports.propertyById = async (req, res) => {
try {
const {propertyId} = _.get(req, 'params'),
propertyData = await bService.getPropertyById(propertyId);
console.log(propertyData);
const propertyPhotoList = [];
async function getPhotoData(item, index){
const id = item.split('#')[1];
const response = await fetch(`http://localhost:4000/api/propertyphoto/${id}`);
const body = await response.json();
console.log(body);
propertyPhotoList.push(body);
}
propertyData.PropertyPhotos.map(getPhotoData);
console.log(propertyPhotoList);
return res.success(res, propertyData);
} catch (err) {
return res.error(res, err.response.status || 500, err.response.statusText || err);
}
}
令我感到困惑的是,异步函数“getPhotoData”中的“console.log(body)”完美地返回了 JSON 对象。
但是异步函数“getPhotoData”之外的数组仍然返回为空,“[]”。
我不确定对象是否没有被成功推送,或者这是否是异步/等待的某种问题。我来自回调所以这对我来说仍然是新的。
我在 Ubuntu 18.10 上使用 Node.js v8.12.0。
原文由 user9158915 发布,翻译遵循 CC BY-SA 4.0 许可协议
两个问题:
您不应该使用
.map
来产生副作用。它返回一个新数组,所以你应该利用它。.map
对async
函数一无所知。您所做的只是创建一系列承诺。当.map
并且您的函数返回时,承诺尚未“完成”。您需要await
所有这些。照这样说: