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
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
})
calling reject() does not stop your program, all codes below will be executed too.
Please update from
if(err) {
console.log('2') // DOES run
reject(new Error(err))
}
resolve(res.field) //Program crashes here because reject didn't actually reject
to
if(err) {
console.log('2') // DOES run
reject(new Error(err))
}
else {
resolve(res.field) //Program crashes here because reject didn't actually reject
}
* update * or you can shorten your code to
if(err) {
console.log('2') // DOES run
return reject(err) // no need to new Error object
}
resolve(res.field) //Program crashes here because reject didn't actually reject
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With