【问题标题】:Loop through ajax function using promises使用 Promise 循环 ajax 函数
【发布时间】:2016-07-08 07:30:10
【问题描述】:

我刚开始研究es6-promises,但我很难理解它。在我的应用程序中,我试图通过 ajax 调用返回数据并继续循环,直到找不到更多数据(本质上是分页)。

这里是返回 promise 对象的 ajax 调用:

function getDeals(start, url) {
   return Promise.resolve($.ajax({
        type: 'GET',
        url: url,
        data: { start: start },
        global: false,
        success: function() {},
        error: function() {}
    }));
}

这里是包含函数:

var start = 0;

getDeals(start, url).then(function (data) {
    // The call returns a more data flag if there are more records
    moreData = data.moreData;
    start = data.records.count;
}).then(function () {
    if (moreData) {
        // Here is where I want to continue calling the function 
        // until no more records are found
        getDeals(start, url);
    }
});

每个调用返回 100 条记录,所以我需要继续循环,直到 moreData 标志为 false。此外,不确定 promise 方法是否是最有效的方法。

【问题讨论】:

  • 如果您可以控制服务器端方法,您可以将 moreData 更改为 total ,而不是等待每个调用完成,您可以生成多个请求,但是您必须开始跟踪并添加一个有点复杂。

标签: javascript jquery json ajax es6-promise


【解决方案1】:

$.ajax 已经为您返回了一个 Promise,因此您无需创建另一个 Promise,只需传入您要运行的成功和失败函数即可。

function getDeals(start, url, success, error) {
    $.ajax({
        type: 'GET',
        url: url,
        data: { start: start },
        global: false,
        success: success,
        error: error
    });
}

然后调用它

var start = 0;

getDeals(start, url, success);

function success (data) {
    // The call returns a more data flag if there are more records
    moreData = data.moreData;
    start = data.records.count;
    if (moreData) {
    // Here is where I want to continue calling the function 
            // until no more records are found
        getDeals(start, url, success);
    }
}

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多