解决 Nodejs 嵌套映射函数中的 Promise 并从 API 调用返回对象数组

我正在尝试从我的数据库中获取一个愿望清单。我已将其保存为以下格式:

{
    "_id": {
       "$oid": "61006dc65892920d3cadefea"
    },"movieId": 240,"__v": 0
}

其中 movieId 是我用来将电影保存到心愿单的字段。这是我用于上述文档结构的模型类:

const mongoose = require('mongoose');

const wishlistSchema = new mongoose.Schema({
   movieId: {type: Number},});

module.exports = new mongoose.model('wishlist',wishlistSchema);

在我的控制器文件中,为了获取心愿单集合中的总项目数,我尝试了这种方法

1. Check if wishlist is empty or not and send response
2. If not empty,get the Object Ids as a list (since the object id represents the totality of the fields in that document)
3. Loop over the object ids list and get the field I'm looking for - movieId field
4. Make an api request to TV Maze api using the movieId,to get the full movie details
5. Send back the list of recovered movie details as response to the user

这种方法只适用于第 4 步。我坚持一些无法解决的承诺。这是我的控制台日志中的消息:

解决 Nodejs 嵌套映射函数中的 Promise 并从 API 调用返回对象数组

这是下面的测试终点图像,以说明我希望作为响应发送给用户的内容:

解决 Nodejs 嵌套映射函数中的 Promise 并从 API 调用返回对象数组

这是我的控制器的完整代码:

module.exports = {
fetchAll: async (req,res,next) => {
    try {
        const wishlist = await Wishlist.find({});
        if (wishlist == null) {
            res.status(404)
                .json({
                    success: false,msg: 'No Movies Found in Wishlist',wishlist: []
                })
        }

        const objectIds = wishlist.map((item) => item.id);
        
        const showsArr = objectIds.map( async (id) => {
            const moviesFound = await Wishlist.find({'_id': id});

            var shows;

            var data = moviesFound.map( async (movie) => {
                shows = await axios.get(`https://api.tvmaze.com/shows/${movie.movieId}`);
                return shows.data;
            });
            console.log(data);
            return data;
        })

        const wishlistItems = await showsArr;
        console.log(wishlistItems);

        return res.status(200)
                  .json({
                    length: showsArr.length,success: true,msg: 'All Movies in Wishlist Fetched',wishlist: wishlistItems
                  })
    } catch (err) {
        console.log(err);
        next(err);
    }
},.... other methods
}

如何解决这些承诺并将电影项目对象的数组发送回给用户?谢谢

gouihk7 回答:解决 Nodejs 嵌套映射函数中的 Promise 并从 API 调用返回对象数组

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/19227.html

大家都在问