繁体   English   中英

Java脚本承诺-如果语句返回最佳实践

[英]Java Script Promises - If Statement Return Best Practices

我正在编写一个node.js函数,该函数根据条件cod返回不同的promise:

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 +)Promise语法,则必须链接promise(这没什么不好的!)。

但是,您也可以选择将代码拆分为多个函数,以提高可读性并避免嵌套问题

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
  }
}

或混合两种解决方案。

一个简单的建议,(这应该起作用)在resolve的参数中传递条件, 然后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告诉我,嵌套诺言是一种不好的做法。

disable the linter on this statement. 只要告诉它可以在此语句禁用lint。 承诺具有精确嵌套的能力,因此您可以在需要时嵌套它们,这就是其中一种情况。 您的代码很好。

似乎您已经使它复杂化了。 then方法已经返回了一个Promise,因此您无需在其中放入Promise.resolve。

您可以为简单起见

return condition
  ? promise.then(() => value)
  : anotherPromise

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM