Search code examples
node.jsasynchronouspromiseasync-awaitexpress-graphql

how can I wait for books data getting from graphql client in async function?


I want to wait for books data getting from graphql query before sending response object

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

I wanted to know what changes should I do ?? in the code so that response will contain "books" key

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

Solution

  • You can use Promis.all with map.

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