我正在编写一个使用 Google API 的模块,但我将所有基于回调的内容包装在一个 promise 中。这是问题区的代码
文件1.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
})
文件2.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
})
})
}
对 auth
的调用工作正常,但对 search
(更具体地说是 googleapi.somemethod
)的调用失败了,并且err
已定义。我检查错误,然后 console.log('2')
运行,但是 catch
中的 console.log('1')
没有不运行,不抛出错误,并且程序在 resolve(res)
上崩溃,因为 res
未定义。我试过将错误捕获器作为 then
的第二个参数而不是使用 catch
,但这仍然不起作用
api.search('example').then(res => {
...do some stuff...
}, err => {
console.log('2') // Still doesn't run
throw err
})
我正在运行 Node v6.2.1
最佳答案
你应该返回 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
})
此外,如果您不需要 search
中的 auth
,那么您可以取消嵌套这些 promise:
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
})
关于javascript - promise 拒绝在回调内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37805121/