javascript - 如何更改 jquery promise 链中的解析值

标签 javascript jquery promise jquery-deferred

我正在尝试编写一个可以在更改解析值的 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/

相关文章:

javascript - 如何使用 javascript/jQuery 增加/减少十六进制颜色值

web-services - 如何使用 AngularJS 进行顺序 Rest Web 服务调用?

javascript - 如何知道nginx是否正在压缩gzip?

jquery - 如何使用 jquery 在 iframe 中选择标签?

javascript - 需要使用jquery提取XML节点,其中节点的sibling等于某个值;现在使用 xPath

javascript - 如何使用嵌套 HTTP 请求更新我的字典?

javascript - 使用 Bluebird 链接多个请求

javascript - Angular.js - 使用间隔应用过滤器

javascript - 如何将毫秒数转换为时间跨度以在 Google 图表中使用?

javascript - 美图 : Label Names in Vertical Axes Stack Charts