[英]How to pass arguments to function as then()'s argument in Promise chain with previous resolved value being kept?
[英]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.