如何在Array.map遍历中使用异步方法

273 阅读1分钟

最近在使用koa开发后端的时候,遇到了一个难题。

开发一个展示博文列表的接口,需要每个列表项携带至少三个图片作为封面

const result = await Blog.findAndCountAll({        limit: pageSize, // 每页多少条        offset: pageSize * pageIndex, // 跳过多少条        order: [['id', 'desc']], //倒序查询展示最新列表        where: {            typeId: type        },        // 连表查询        include: [            {                model: User,                attributes: ['userName', 'nickName', 'picture'],                where: userWhereOpts            }        ]    }) let blogList = result.rows.map((row) => row.dataValues)

确实是获取了blogList这个项,现在我需要给blogList的每一项都添加一个images属性,该属性为数组

所以我先是定义了这样一个方法获取另一张表中的images数组,但是这个方法是异步的,问题就在这里:

async function _getImagesByBlogId(blogId) {    const result = await Image.findAndCountAll({        where: {            articleId: blogId        }    })    console.log(result)    let imageList = result.rows.map((row) => row.dataValues)    return imageList}

我需要遍历blogList的每一项,添加images属性:

 blogList = await Promise.all(blogList.map(async (blogItem) => {        const user = blogItem.user.dataValues        const images = await _getImagesByBlogId(blogItem.id)        blogItem.user = formatUser(user)        blogItem.images = images        return blogItem    }));

最后把结果返回出去就ok了,附上数据结构:

{"errno":0,"data":
    {"isEmpty":false,
    "blogList":[{"id":1,
"userId":1,"title":"静夜思",
"author":"李白","videoSrc":null,"content":"","image":null,
"showType":3,"typeId":1,"created_at":"2020-04-14T17:10:30.000Z",
"updated_at":"2020-04-03T17:10:23.000Z","deleted_at":null,
"user":{"userName":"zhangsan","nickName":"","picture":""},
"createdAtFormat":"2020 04 15 01:10",
"updatedAtFormat":"2020 04 04 01:10","images":[{"id":1,"articleId":1,"type":"",
"imageUrl":"1.png","created_at":"2020-04-03T17:24:50.000Z",
"updated_at":"2020-04-03T17:24:54.000Z","deleted_at":null}]}],
"pageSize":10,"pageIndex":0,"count":1}}