【问题标题】:Promise - Call a function in between two promisesPromise - 在两个 Promise 之间调用一个函数
【发布时间】:2017-01-28 06:37:01
【问题描述】:

我有两个请求和一些函数要在两者之间调用。流程是,当第一个 Promise 被调用并完成时,无论结果是什么(成功或失败),都应该调用一些与 Promise 无关的函数,并且只有在我们调用第二个 Promise 之后。所以这就是我最终这样做的方式,这看起来不是一个好的解决方案。

funtionReturnsPromise()
    .then(()=>{})
    .catch(()=>{})
    .then(()=>{
        nonPromiseRelatedFuntion()
    })
    .then(()=>{
        return funtionReturnsPromise2()
    })

【问题讨论】:

  • then() 中的所有内容都与 Promise 相关。您必须将代码放在承诺代码之前或之后。如果你想让它与一个承诺无关,你不能把它放在中间。
  • 为什么你认为这不是一个好的解决方案?
  • 我不确定,但你不能在第一个承诺的最后一行使用回调吗?
  • 如果你对错误做了一些事情,你的例子看起来不会那么奇怪——你可能想在“现实世界”中以某种方式记录/处理它,然后你的例子就变得非常好了。它基本上完全遵循example 所做的标题为Using and chaining the catch method
  • 如果nonPromiseRelatedFuntion 是异步的(即“有回调”)并且你想在承诺链中等待它,你必须promisify它。像 bluebird 这样的库有promisification 的助手。

标签: javascript promise es6-promise


【解决方案1】:

由于所需的流量是:

Promise > Function > Promise

无论第一个 Promise 的结果如何,在哪个函数上执行,您都可以简单地执行以下操作:

function secondFunction(outcome) {
  // do stuff
  
  return funtionReturnsPromise2()
}

functionReturnsPromise().then(secondFunction).catch(secondFunction)

现在,关于另一个话题,我不会将第二个函数称为“无关”,因为根据您的解释,它显然需要在第一个承诺完成后调用。

【讨论】:

    【解决方案2】:

    假设nonPromiseRelatedFuntion 是同步的并且您对functionReturnsPromise 的返回值不感兴趣

    functionReturnsPromise()
    .then(
      // no matter what happens, the function is invoked
      () => { nonPromiseRelatedFunction() },
      error => { 
        nonPromiseRelatedFunction()
        // do error handling from functionReturnsPromise
      } 
    )
    .then(() => functionReturnsPromise2() }
    .catch(console.error)
    

    如果你需要一个值:

    functionReturnsPromise()
    .then(
      value => {
        nonPromiseRelatedFunction()
        return functionReturnsPromise2(value)
      },
      error => { 
        nonPromiseRelatedFunction()
        // do error handling from functionReturnsPromise
      } 
    )
    .catch(console.error) // error handling from functionReturnsPromise2
    

    【讨论】:

      【解决方案3】:

      就像我假设的其他答案一样

      • nonPromiseRelatedFunction 是同步的
      • 你真的不关心任何返回值
      • nonPromiseRelatedFunction funtionReturnsPromise2 应在所有情况下执行

      阅读了ALL问题的cmets,我明白以上毕竟不是假设

      最简单的解决办法是去掉第一个.then

      funtionReturnsPromise()
          .catch(()=>{})
          .then(()=>{
              nonPromiseRelatedFuntion()
          })
          .then(()=>{
              return funtionReturnsPromise2()
          })
      

      注意:这样的代码可以写

      funtionReturnsPromise()
          .catch(()=>{})
          .then(nonPromiseRelatedFuntion)
          .then(funtionReturnsPromise2)
      

      当然,最后两个函数会接收参数,但如果这些函数中的代码无论如何都会忽略参数,那么它们就没有问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多