在异步功能中推送到数组不起作用 [英] Pushing to an array in async function not working
问题描述
这是我的代码:
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对象.
What's confusing me it that the 'console.log(body)' inside the asynchronous function 'getPhotoData' is returning the JSON object perfectly fine.
但是异步函数'getPhotoData'之外的数组仍返回为空的[[]'.
But the array outside of the asynchronous function 'getPhotoData' is still returning as empty, '[]'.
我不确定对象是否被成功推送,或者这是否与异步/等待有关.我来自回调,所以这对我来说仍然是新的.
I am unsure whether the object is not being successfully being pushed, or if this is some sort of issue with async/await. I am coming from callbacks so this is still new to me.
我正在Ubuntu 18.10上使用Node.js v8.12.0.
I am using Node.js v8.12.0 on Ubuntu 18.10.
推荐答案
两个问题:
-
您不应使用
.map
产生副作用.它返回一个新数组,因此您应该使用它.
You shouldn't be using
.map
for side effects. It returns a new array so you should make use of that.
.map
对async
函数一无所知.您正在做的只是创建一系列承诺.当.map
并且函数返回时,promise还没有完成".您需要全部await
.
.map
doesn't know anything about async
functions. All you are doing is creating an array of promises. When .map
and your function returns, the promises are not "done" yet. You need to await
all of them.
话虽如此:
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)
);
这篇关于在异步功能中推送到数组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!