【问题标题】:How to change the resolved value in a jquery promise chain如何更改 jquery 承诺链中的解析值
【发布时间】:2017-10-25 18:36:09
【问题描述】:

我正在尝试编写一个可以在更改解析值的承诺链中使用的函数。

下面,我希望函数 getAndChangeValue() 将解析的参数从“Hello”更改为“Bye”。请帮忙!我似乎无法理解它。 :-)

https://plnkr.co/edit/RL1XLeQdkZ8jd8IezMYr?p=preview

getAndChangeValue().then(function(arg) {
    console.log(arg) // I want this to say "Bye"
});


function getAndChangeValue() {

    var promise = getValue()
    promise.then(function(arg) {
        console.log('arg:', arg) // says "Hello"

        // do something here to change it to "Bye"
    })
    return promise
}

function getValue() { // returns promise

    return $.ajax({
        url: "myFile.txt",
        type: 'get'

    });
}

【问题讨论】:

  • 这是一个非常奇怪的要求。如果您要忽略返回的内容,为什么还要麻烦发出 AJAX 请求?
  • 是的,这不是必需的。我只是在创建一个虚假的概念验证情况。我可以做一个超时,或者类似的事情

标签: javascript jquery promise jquery-deferred


【解决方案1】:

你可以在传递给then()的函数中返回任何你喜欢的值,但你必须返回then()返回的新承诺,而不是原来的promise

function getAndChangeValue() {
    return getValue().then(function(arg) {
        return "Bye";
    }
}

【讨论】:

  • 那么改变它的唯一方法就是创建一个新的 Deferred 对象? (我希望不要——我认为不重复使用相同的承诺是一种反模式)
【解决方案2】:

如果您使用的是BluebirdJS,则可以添加.return(value)

例如:

var firstPromise = new Promise(function (resolve, reject) { 
   return resolve('FIRST-VALUE'); 
})
.then(function (response) {
   console.log(response); // FIRST-VALUE
   var secondPromise = new Promise(function (resolve) { 
      resolve('SECOND-VALUE');
   });

   // Here we are changing the return value from 'SECOND-VALUE' to 'FIRST-VALUE'
   return secondPromise.return(response); 
})
.then(function (response) {
   console.log(response); // FIRST-VALUE
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2019-09-25
    • 2016-04-02
    • 1970-01-01
    • 2016-06-22
    • 2012-07-17
    • 1970-01-01
    相关资源
    最近更新 更多