如何更改 jquery 承诺链中的解析值



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

下面,我希望函数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'
    });
}

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

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

如果您使用的是 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
})

最新更新