我有以下代码在callbacks
中使用promises
:
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}`)
})
}
我的问题:
在性能或最佳实践意义上,可以将'callback' function
称为承诺中的两种方式,或者我做错了什么,我的意思是一些承诺反模式方式?
这似乎真的是倒退,并且从承诺管理错误并将其传递到链中的好处中消失了
从函数返回异步promise,不要用回调中断它。然后在链的末尾添加一个catch
const myFunction = (someParam) => {
// return the promise
return someAsyncOperation(someParam) // this function returns an array
.then((array) => {
return array.includes(clue) ? array : [];
});
}
myFunction(someParam).then(res=>{
if(res.length){
// do something with array
}else{
// no results
}
}).catch(err=>console.log('Something went wrong in chain above this'))
不要使用promises内部的回调,这是一种反模式。一旦你已经承诺,只需使用它们。不要“unpromisify”将它们变成回调 - 这在代码结构中向后移动。相反,只需返回承诺,然后您可以使用.then()
处理程序来设置您想要解析的值,或者抛出错误来设置您希望被拒绝的原因:
const clue = 'someValue';
const myFunction = (someParam) => {
return someAsyncOperation(someParam).then(array => {
if (!array.includes(clue)){
// reject promise
throw new Error(`The array does not include: ${clue}`);
}
return array;
});
}
然后,调用者只会这样做:
myFunction(someData).then(array => {
// success
console.log(array);
}).catch(err => {
// handle error here which could be either your custom error
// or an error from someAsyncOperation()
console.log(err);
});
这为您提供了这样的优势:调用者可以使用promises的所有功能将此异步操作与其他任何操作同步,以便轻松地将错误传播到一个错误处理程序,使用await
等等...