如何在异步函数中等待从 GraphQL 客户端获取书籍数据?



我想在发送响应对象之前等待从 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);
}
}

想知道我应该在代码中做什么更改??,以便响应将包含"书籍"键

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);
});
});

您可以将Promis.allmap一起使用。

const booksData = await BPromise.all(
userBookList.map( (book) =>  
this.fastify.graphQLClient.executeQuery(
{ 
query: books.userBooks({ _id: book.book_id })
})
));

最新更新