推送到异步函数中的数组不起作用

新手上路,请多包涵

这是我的代码:

 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 许可协议

阅读 175
2 个回答

两个问题:

  1. 您不应该使用 .map 来产生副作用。它返回一个新数组,所以你应该利用它。

  2. .mapasync 函数一无所知。您所做的只是创建一系列承诺。当 .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)
);

原文由 Felix Kling 发布,翻译遵循 CC BY-SA 4.0 许可协议

您需要使用 Promise.allawait

 await Promise.all(propertyData.PropertyPhotos.map(getPhotoData));

这是带有修复程序的完整代码:

 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);
        }
        await Promise.all(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 的所有调用在发送响应之前完成。

原文由 SimpleJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题