簡體   English   中英

如何更改jQuery Promise鏈中的解析值

[英]How to change the resolved value in a jquery promise chain

我正在嘗試編寫一個可在更改解析值的Promise鏈中使用的函數。

下面,我希望函數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,而不是原始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
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM