0

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

1 回答 1

1

您可以Promis.all使用map.

const booksData = await BPromise.all(
  userBookList.map( (book) =>  
  this.fastify.graphQLClient.executeQuery(
    { 
      query: books.userBooks({ _id: book.book_id })
    })
  ));
于 2018-10-07T13:36:29.980 回答