【发布时间】:2019-02-08 00:46:37
【问题描述】:
我有以下代码在promises 内使用callbacks:
const clue = 'someValue';
const myFunction = (someParam, callback) => {
someAsyncOperation(someParam) // this function returns an array
.then((array) => {
if (array.includes(clue)){
callback(null, array); // Callback with 'Success'
}
else{
callback(`The array does not includes: ${clue}`); // Callback with Error
}
})
.catch((err) => {
// handle error
callback(`Some error inside the promise chain: ${err}`) // Callback with Error
})
}
然后这样称呼它:
myFunction (someParam, (error, response) => {
if(error) {
console.log(error);
}
else {
// do something with the 'response'
}
})
阅读了一些文档,我发现有一些改进的方法可以做到这一点:
const myFunction = (someParam, callback) => {
someAsyncOperation(someParam) // this function returns an array
.then((array) => {
if (array.includes(clue)){
callback(array);
}
else{
callback(`The array does not includes: ${clue}`);
}
}, (e) => {
callback(`Some error happened inside the promise chain: ${e}`);
})
.catch((err) => {
// handle error
callback(`Some error happened with callbacks: ${err}`)
})
}
我的问题:
就性能或最佳实践而言,可以在 Promise 中调用 'callback' function,因为这两种方式都表明,或者我做错了什么,我的意思是一些 Promise 反模式方式?
【问题讨论】:
-
很确定您不应该有 both 错误处理程序(作为
.then的第二个参数)和catch。最好只有一个catch。 -
另请注意,您的第二个代码在成功期间调用
callback并使用array作为第一个 参数(error)而不是第二个参数(response)。 -
不要在 Promise 中使用回调——这是一种反模式。只需返回一个 Promise 并让 Promise 处理完成或错误的通知。这就是它们的设计目的。然后,调用者将在返回的 Promise 上使用
.then()和.catch()而不是回调。这是 Javascript 的现状和未来。 -
不要不承诺!
-
@robe007 - 根据您的要求,我添加了一个答案来说明。
标签: javascript callback promise es6-promise asynccallback