【问题标题】:Using promises and non promises in a chain在链中使用承诺和非承诺
【发布时间】:2015-06-09 13:56:49
【问题描述】:

我有一系列的承诺(主要是 ajax 调用,但也有一些延迟)。

我这样称呼它们,我的问题是我还需要混合一些不返回承诺的标准函数,我在下面进行了尝试,这是正确的方法吗?

基本上我希望promise A、B 和C 运行,然后执行我的非promise 方法,一旦完成,继续执行promise D 和E。

this.promiseA()
.then(this.promiseB)
.then(this.promiseC)
.then(function(){

    //do some methods that do not return promises
})
.then(this.promiseD)
.then(this.promiseE);

【问题讨论】:

  • this 的这些属性是实际的承诺,还是您的意思是返回承诺的函数?这是一个很大的区别。

标签: javascript jquery promise jquery-deferred


【解决方案1】:
this.promiseA()
.then(this.promiseB)
.then(this.promiseC)
.then(function(){

    //do some methods that do not return promises
    // modify original promise here , else original promise
    // passed to next `.then` in chain
    // return $.when(true); 
})
.then(this.promiseD)
.then(this.promiseE);

【讨论】:

  • 谢谢,我只是在没有您何时尝试过,它仍然有效,为什么?
  • @panthro .then() 返回一个新的承诺。
  • 你能解释一下吗
  • @panthro "从 jQuery 1.8 开始,deferred.then() 方法返回一个新的 promise,可以通过函数过滤 deferred 的状态和值," @ 987654321@
  • 但为什么即使没有时间,它仍然会继续这个链条?
【解决方案2】:

then 函数可以发回任何东西,包括未定义的。如果需要,这一切都被封装在一个新的 Promise 中,这样链就可以继续下去。

如果你的函数返回一个 Promise 或 thenable,当这个对象被填满时,链将继续。然后promiseD 会收到这个thenable 的解析值。

如果您的函数返回一个立即值或 null 或未定义,则链将立即继续。 promiseD 将收到所述值。

所以是的,你的解决方案是正确的。

【讨论】:

    猜你喜欢
    • 2016-03-04
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多