0

我正在编写一个库来访问来自服务器的数据,并将格式化的数据返回给我的函数的使用者。这是我想要的一个例子:

// my code
var model = function () {
    return $.ajax(myRequest).done(function (rawData) {
        return treatment(data);
    });
}

// client code
var useModel = function () {
    var modelPromise = model();
    modelPromise.done(function (formattedData) { // consume this result })
}

其中 formattedData 是我第一次完成回调的结果,而不是 rawData。

你有什么想法?

谢谢

R。

4

2 回答 2

1

里吉斯,

jQuery 的.then()文档说:

从 jQuery 1.8 开始, deferred.then() 方法返回一个新的 Promise,它可以通过函数过滤 deferred 的状态和值,替换现在不推荐使用的 deferred.pipe() 方法。

第二个示例.then()类似于您想要的(尽管不涉及 ajax)。

据我所知,对代码的必要更改非常少:

// my code
var model = function () {
    return $.ajax(myRequest).then(function (rawData) {
        return treatment(rawData);
    });
}

// client code
var useModel = function () {
    var modelPromise = model();
    modelPromise.done(function (formattedData) { // consume this result })
}
于 2013-01-25T05:35:47.720 回答
0

里吉斯,

我非常喜欢甜菜根的回答。这是我在尝试自己理解这个概念时所做的一个示例:Multiple asynchronous requests with jQuery

来自 jsFiddle 的来源:

var logIt = function (msg) {
    console.log(((new Date()).toLocaleTimeString()) + ": " + msg);
}, pauseBrowser = function (ms) {
    ms += new Date().getTime();
    while (new Date() < ms) {}
}, dataForService1 = {
    json: JSON.stringify({
        serviceNumber: 1,
        description: "Service #1's data",
        pauseAfterward: 3 // for pausing the client-side
    }),
    delay: 0 // delay on the server-side
}, dataForService2 = {
    json: JSON.stringify({
        serviceNumber: 2,
        description: "Service #2's data",
        pauseAfterward: 1
    }),
    delay: 0 // delay on the server-side
};

function getAjaxConfiguration() {
    return {
        type: 'POST',
        url: '/echo/json/',
        success: function (data) {
            var msg = "Handling service #" + data.serviceNumber + "'s success";
            logIt(msg);
            logIt(JSON.stringify(data));
        }
    };
}

var async2 = function () {
    var ajaxConfig = $.extend(getAjaxConfiguration(), {
        data: dataForService2
    });
    return $.ajax(ajaxConfig);
};

var async1 = function () {
    var ajaxConfig = $.extend(getAjaxConfiguration(), {
        data: dataForService1
    });
    return $.ajax(ajaxConfig);
};

var do2AsynchronousFunctions = function () {
    var dfd = new $.Deferred();

    async1()
    .then(function (async1ResponseData) {
        logIt("async1's then() method called, waiting " + async1ResponseData.pauseAfterward + " seconds");
        pauseBrowser(async1ResponseData.pauseAfterward * 1000);
    })
    .done(function (a1d) {
        logIt("async1's done() method was called");
        return async2()
        .then(function (async2ResponseData) {
            logIt("async2's then() method called, waiting " + async2ResponseData.pauseAfterward + " seconds");
            pauseBrowser(async2ResponseData.pauseAfterward * 1000);
        })
        .done(function (a2d) {
            logIt("async2's done() method was called");
            dfd.resolve("final return value");
        });
    });

    return dfd.promise();
};

$.when(do2AsynchronousFunctions()).done(function (retVal) {
    logIt('Everything is now done! Final return value: ' + JSON.stringify(retVal));
});
于 2013-01-25T17:40:01.017 回答