我想在发送响应对象之前等待从graphql查询获取的图书数据
async getUserBookList(req, res) {
let responseObj = {};
const validationRes = this.validateGetUserBookList(req);
const userId = req.params.id;
try {
const userBookList = await dbHelper.filterQuery(
{ user_id: userId },
"userbook"
);
const data = userBookList;
/**
* DESCRIPTION: Gets Books based on bookId
* PARAMS: _id!: string
* RETURNS: books: [Book]
*/
await userBookList.map(book => {
this.fastify.graphQLClient
.executeQuery({
query: books.userBooks({ _id: book.book_id })
})
.then(result => {
// => here the book is getting added
data["books"] = [result.data.books];
console.log(data);
});
});
res.send(data);
} catch (err) {
res.send(err);
}
}
我想知道应该怎么做?在代码中,以便响应将包含“ books”键
await userBookList.map(book => {
this.fastify.graphQLClient
.executeQuery({
query: books.userBooks({ _id: book.book_id })
})
.then(result => {
// => here the book is getting added
data["books"] = [result.data.books];
console.log(data);
});
});
答案 0 :(得分:1)
您可以将Promis.all
与map
一起使用。
const booksData = await BPromise.all(
userBookList.map( (book) =>
this.fastify.graphQLClient.executeQuery(
{
query: books.userBooks({ _id: book.book_id })
})
));