1

I am battling to get the syntax right for a graphQL resolver that needs to return the value gotten from a web API, which happens asynchronously. The console logging of sounds shows my list of sound objects just fine, but I can't get it returned back by the resolver as the result of the query.

I have tried a number of things and have Googled extensively, but still cannot find the magic incantation to get the resolver to wait for the results of the web queries (it takes two, one to establish an API connection, the other to actually fetch the sound list):

var serviceProvider = require('provider-api)

  Query: {
    sounds: () => {
      serviceProvider.connect('http://soundsource.foo', 'userName', 'pass')
      .then (function (client) {
          client.sounds.list()
          .then (function (sounds) {
            console.log('Got some sounds ' + sounds)
          })
      .catch(function (err) {
        console.log('Error in sounds query ' + err)
        })
      })
      return sounds
  },
}

So far everything I have tried (dozens of variants of the code above) has resulted in the same thing: the returned object is null.

capouch
  • 557
  • 1
  • 5
  • 16

1 Answers1

2

The return statement is outside of the Promise chain. Also, sounds variable is not returned from .then(). Consider adjusting the name of the parameter at .then() to avoid confusion as to which sounds variable that you are referencing

var serviceProvider = require('provider-api)

  Query: {
    sounds: () => {
      return serviceProvider.connect('http://soundsource.foo', 'userName', 'pass')
      .then (function (client) {
          return client.sounds.list()
          .then (function (_sounds) {
            console.log('Got some sounds ' + _sounds)
            return _sounds
          })
          .catch(function (err) {
            console.log('Error in sounds query ' + err);
            return err
          })
      })
      .catch(function(err) {
        console.log(err)
      })
  },
}
guest271314
  • 1
  • 15
  • 104
  • 177
  • 2
    I had tried the identical logic, **except** I didn't do a return on the first promise in the chain. Doh!! Thanks so much!! – capouch Sep 23 '17 at 22:29