graphQL解析器不等待Web API完成

时间:2017-09-23 20:22:27

标签: javascript node.js promise graphql

我正在努力为graphQL解析器提供正确的语法,该解析器需要返回从Web API获取的值,这是异步发生的。声音的控制台记录显示我的声音对象列表很好,但是我无法通过解析器将其作为查询结果返回。

我已经尝试了很多东西,并且广泛使用Google搜索,但仍然无法找到让解析器等待Web查询结果的神奇咒语(需要两个,一个用于建立API连接,另一个用于实际上获取声音列表):

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
  },
}

到目前为止,我所尝试的一切(上面代码的几十种变体)都产生了同样的结果:返回的对象是null

1 个答案:

答案 0 :(得分:2)

attempted return { _id: 2, username: 'TINA', email: 'tina@gmail.com', password: '1234', name: 'TIN', super_user: 0 } (node:105576) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined (node:105576) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. { _id: 59c2fc904300338c08a8359c, name: 'Ryan Igo', email: 'rigo@cfevans.com', username: 'rigo', password: '$2a$10$doYAezUZ/bzOFKQEbTPrTOb2RiF33cH3N8G/N/nuxaKFvzpFjC6H.', __v: 0, procore_projects: [ ], procore_companies: [], procore: { created_at: '1506083587', refresh_token: '4e4d6c962884671e116938141de707b59eab8c442f8ae39bdad79255b6b183da', expires_in: '7200', access_token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJhaWQiOiI3NDNkNmJiYzYyNGNiMWM5YzU2MDczMzMzMzgwY2FlN2QzN2Y0ODQ0NTgwZTFiZGIxZDM2MzAwNTgzZjg3ZTEwIiwiZXhwIjoxNTA2MDkwNzg3LCJ1aWQiOjI3NzkxOH0.AD9Sk2AcsLLrH1OtCUg8cnh3tOFq5vyQTetsBN1J29anrUXEr2nW40rENmkZLj1wPxfjnhW0Vp03spEYYAr-MRB7AFX9HgUQ_5sUa34hgbg0Vd5biwX4FluhqSJ8_73lEsO59xPSedpmD_vQC7dwaAa4NU8uVhhMm6VaDYCXrHvGZ74N' } } 语句位于return链之外。此外,Promise不会返回sounds变量。请考虑调整.then()处参数的名称,以避免混淆您引用的.then()变量

sounds