Weston Weston - 5 months ago 21
Node.js Question

Promise reject not working inside of callback

I'm writing a module that uses the Google API, but am wrapping everything that is callback based in a promise. This is the code of the problem area

file1.js

var File2 = require('file2')
var api = new File2()
api.auth().then(auth => {
api.search('example').then(res => {
...do some stuff...
})
}).catch(err => {
console.log('1') //Not being run
throw err
})


file2.js

class File2(){
auth() {
...works fine and resolves...
}

search() {
return new Promise((resolve, reject) => {
googleapi.somemethod(options, (err, res) => {
if(err) {
console.log('2') // DOES run
reject(new Error(err))
}
resolve(res.field) //Program crashes here because reject didn't actually reject
})
})

}


The call to
auth
is working just fine, but the call to
search
(and more specifically
googleapi.somemethod
) is failing, and
err
is defined. I check for err, and
console.log('2')
runs, but then
console.log('1')
in
catch
doesn't run, the error isn't thrown, and the program crashed on
resolve(res)
because
res
is undefined. I've tried putting the error catcher as the second argument to
then
instead of using
catch
, but that still doesn't work

api.search('example').then(res => {
...do some stuff...
}, err => {
console.log('2') // Still doesn't run
throw err
})


I'm running Node v6.2.1

Answer

You should return the promise:

var File2 = require('file2')
var api = new File2()
api.auth().then(auth => {
  return api.search('example').then(res => { // return the promise
     return ...
  })
}).catch(err => {
  console.log('1') // Not being run
  throw err
})

Also, if you don't need auth inside search then you can unnest those promises:

var File2 = require('file2')
var api = new File2()
api.auth().then(auth => {
  return api.search('example')
}).then(res => {
   return ...
}).catch(err => {
  console.log('1') //Not being run
  throw err
})