0

I'm using the aws-amplify package to do GraphQL queries. I've written a generic GraphQL class to encapsulate this logic, but I can't resolve the promise correctly.

I instantiate the class with no problems and call the query like this:

let api = new GraphQL({
      operation: 'listBillingCustomers',
      args: `count: ${queryLimit}`
    });


let customerResults = api.query();

The query function in my GraphQL class looks like this:

query() {
    this.queries.forEach((qry) => {
      if (qry.name === this.operation) {
        API.graphql(graphqlOperation(qry(this.arguments)))
          .then((result) => {
            return result;
          })
          .catch(result => {
            const { errors } = result;
            return errors;
          });
      }
    })
  }

It does the API call and returns the data I need, but the code that calls this function won't wait on the promise to resolve, resulting in that being undefined.

I don't understand how to work with the amplify library's graphqlOperation so that I can use the promise correctly. If I put a console.log in the class's query() function, it ultimately resolves and gives me my data. But that's after it's continued in the main function where I instantiate the class.

greenie-beans
  • 440
  • 1
  • 5
  • 15
  • `forEach` shouldn't be used with Promises. Use `Promise.all` and make sure you either return the resulting Promise, or else await it and then return the result. – Daniel Rearden Feb 10 '20 at 20:59
  • thanks! i ended up using a map instead of an array, so i didn't even need to loop at all. – greenie-beans Feb 10 '20 at 21:41

0 Answers0