这是我的代码:
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。
两个问题:
你不应该使用.map
对于副作用。它返回一个新数组,因此您应该使用它。
.map
什么都不知道async
功能。你所做的就是创造一系列承诺。什么时候.map
当你的函数返回时,承诺还没有“完成”。你需要await
他们全部。
照这样说:
async function getPhotoData(item, index){
const id = item.split('#')[1];
const response = await fetch(`http://localhost:4000/api/propertyphoto/${id}`);
return await response.json();
}
const propertyPhotoList = await Promise.all(
propertyData.PropertyPhotos.map(getPhotoData)
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)