因此,在这一点上, promise 作为“最佳实践”似乎比回调更具吸引力,但许多现有库仍然使用回调。
因此,给定一个已经实现如下回调模式的库:
library.connect(function(err) {
library.someQuery({}).exec(function(err, result) {
// some code
library.someQuery(result).exec(function(err2, result2) {
// some code
})
})
})
将这些回调包装在 Promise 中以避免嵌套有好处吗?
new Promise((resolve, reject) => {
library.connect(function(err) {
if (err) reject(err)
else resolve()
}
}).then(() => {
return new Promise((resolve, reject) => {
library.someQuery({}).exec((err, result) => {
if (err) reject(err)
else resolve(result)
}
})
}).then((result) => {
return new Promise((resolve, reject) => {
library.someQuery(result).exec(function(err2, result2) {
if (err) reject(err2)
else resolve(result2)
}
}).then((result) => {
// some code
}).catch((err) => // handle error)
没有嵌套会更好,但会更冗长。我也不确定这会带来多少额外的好处。也许更好的错误处理?
最佳答案
在您的第一个代码片段中,您有多个位置来处理错误,而对于 Promise,您只有一个位置。
我认为你做了一些很好的观察,还补充说,使用 promise 会对性能产生轻微的开销。但是,如果您可以忍受重复的代码,那么您可能会使用它们获得更容易调试的代码。
您还可以创建一个小函数来抽象 promise ,但请记住,这会增加一点开销:
// Non tested code, but hopes it shows a point
function make_promisable(context, method) {
return new Promise((resolve, reject) => {
context[method]((err, result) => {
if (err) reject(err);
else resolve(result);
});
});
};
// Note: The below actually seems to hide the logic in the code,
// is this any good, or harder to read/debug?
make_promisable(library, 'connect').then(() => {
return make_promisable(library.someQuery({}), 'exec');
}).then((result) => {
return make_promisable(library.someQuery(result), 'exec');
}).then((result) => {
// some code
}).catch((err) => // handle error)
关于javascript - 将现有 API 的回调包装在 promise 中以避免 "callback hell"有好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34600781/