如何更改 jquery 承诺链中的解析值
How to change the resolved value in a jquery promise chain
我正在尝试编写一个可以在更改已解析值的承诺链中使用的函数。
下面,我希望函数 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'
});
}
您可以 return 传递给 then()
的函数中您喜欢的任何值,但您必须 return return 由 then()
而不是原来的 promise
:
function getAndChangeValue() {
return getValue().then(function(arg) {
return "Bye";
}
}
如果您正在使用 BluebirdJS you are able to add .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
})
我正在尝试编写一个可以在更改已解析值的承诺链中使用的函数。
下面,我希望函数 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'
});
}
您可以 return 传递给 then()
的函数中您喜欢的任何值,但您必须 return return 由 then()
而不是原来的 promise
:
function getAndChangeValue() {
return getValue().then(function(arg) {
return "Bye";
}
}
如果您正在使用 BluebirdJS you are able to add .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
})