代码之家  ›  专栏  ›  技术社区  ›  Hatchi Roku

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

  •  0
  • Hatchi Roku  · 技术社区  · 7 年前

    我在写一篇 node.js 根据条件返回不同承诺的函数,cod:

    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 在这两种情况下将执行回调。

    处理这个案件的最佳做法是什么?

    4 回复  |  直到 7 年前
        1
  •  1
  •   Dario user1520615    7 年前

    如果使用Classic(ES6/ES2015+)Promise语法,则必须链接Promise(这一点也不错!).

    但您也可以选择将代码拆分为函数,以获得可读性和 avoid nesting issues :

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

    或者混合两种溶液。

        2
  •  0
  •   Raja Nand Sharma    7 年前

    一个简单的建议(这应该有效)通过解析的参数中的条件,并在 然后 阻止。下面的伪代码将更好地说明这一点:

    (() => {
        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
         }
    })
    
        3
  •  0
  •   Bergi    7 年前

    埃斯林特告诉我,隐瞒承诺是一种不好的做法。

    只是 告诉他 闭嘴 禁用此语句的linter。承诺具有精确嵌套的能力,以便您可以在需要时嵌套它们,这就是其中之一。你的密码没问题。

        4
  •  0
  •   vbranden    7 年前

    好像你把事情搞得太复杂了。then方法已经返回了一个promise,因此您不需要在其中放置promise.resolve。

    为了简单起见

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