我正在编写一个node.js
函数,该函数根据条件返回不同的承诺,即编码:
if(condition){
return promise.then(() => {
return Promise.resolve(value)
})
}else{
return anotherPromise
}
现在的问题是,如果条件为真,我需要在承诺实现后做一些事情,但在另一种情况下,我只是返回承诺,所以eslint
告诉我嵌套承诺是一种不好的做法。所以这段代码对我不起作用:
(() => {
if(condition){
return promise
}
}else{
return anotherPromise
}
}).then(() => {
return Promise.resolve(value)
})
因为使用此代码,then
回调将在两种情况下执行。
处理此案例的最佳实践是什么?
如果你使用经典(ES6/ES2015+(承诺语法,你必须链接承诺(没什么不好的!
但是,您也可以选择将代码拆分为函数以获得可读性并避免嵌套问题:
const firstCase = () => ... // returning a promise
const secondCase = () => ... // returning a promise
if (condition) {
return firstCase()
} else {
return secondCase()
}
但是在 ES7/ES2016+ 中,您可以使用 async/await 语法:
// in a "async" function
async function main() {
if (condition) {
await promise // if you need the promise result, you can assign it
return value // the result of an async function is always a Promise.
} else {
return anotherPromise
}
}
或混合使用两种解决方案。
一个简单的建议,(这应该有效(在解析的参数中传递条件并在then块中检查它。下面的伪代码将更好地阐明它:
(() => {
if(condition){
return new Promise((resolve,reject)=>{
//Some tasks
resolve(condition)
//Some reject condition
reject()
})
}
else {
return new Promise((resolve,reject)=>{
//Some tasks
resolve(condition)
//Some reject condition
reject()
})
}
}).then((condition) => {
if(condition) {
//Do something
}
else {
//Do Nothing
}
})
eslint 告诉我,嵌套承诺是一种不好的做法。
只需告诉它关闭***禁用此语句上的linter。承诺能够精确嵌套,以便您可以在需要时嵌套它们,这就是其中一种情况。你的代码很好。
似乎你把它复杂化了。then 方法已经返回了一个承诺,因此您无需在其中放置 Promise.resolve 。
为了简单起见,您可以这样做
return condition
? promise.then(() => value)
: anotherPromise