我正在尝试编写一个可以在更改解析值的 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";
}
}
关于javascript - 如何更改 jquery promise 链中的解析值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231556/