Wes*_*ton 1 javascript error-handling callback node.js promise
我正在编写一个使用Google API的模块,但是在承诺中包装了所有基于回调的内容。这是问题区域的代码
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
})
Run Code Online (Sandbox Code Playgroud)
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
})
})
}
Run Code Online (Sandbox Code Playgroud)
对的调用auth工作正常,但是对search(更具体而言googleapi.somemethod)的调用失败了,并且err已定义。我检查错了,并console.log('2')运行,但随后console.log('1')在catch不运行时,没有引发错误,程序崩溃的resolve(res)原因res是不明确的。我尝试将错误捕获器作为第二个参数,then而不是使用catch,但这仍然不起作用
api.search('example').then(res => {
...do some stuff...
}, err => {
console.log('2') // Still doesn't run
throw err
})
Run Code Online (Sandbox Code Playgroud)
我正在运行Node v6.2.1
您应该退还诺言:
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
})
Run Code Online (Sandbox Code Playgroud)
另外,如果您不需要auth内部,search则可以取消这些承诺:
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
})
Run Code Online (Sandbox Code Playgroud)
调用reject()不会停止你的程序,下面的所有代码也将被执行。
请更新自
if(err) {
console.log('2') // DOES run
reject(new Error(err))
}
resolve(res.field) //Program crashes here because reject didn't actually reject
Run Code Online (Sandbox Code Playgroud)
到
if(err) {
console.log('2') // DOES run
reject(new Error(err))
}
else {
resolve(res.field) //Program crashes here because reject didn't actually reject
}
Run Code Online (Sandbox Code Playgroud)
* 更新 * 或者您可以将代码缩短为
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5003 次 |
| 最近记录: |