使用 promises 遍历 ajax 函数
Loop through ajax function using promises
我刚开始研究 es6-promises,但我无法理解它。在我的应用程序中,我试图通过 ajax 调用获取 return 数据并继续循环,直到找不到更多数据(本质上是分页)。
这是 ajax 调用,其中 return 是一个承诺对象:
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);
}
});
每次调用 returns 100 条记录,所以我需要继续循环直到 moreData 标志为 false。此外,不确定 promise 方法是否是执行此操作的最有效方法。
$.ajax 已经 returns 为您提供了一个承诺,因此您无需再创建一个,只需传入您想要 运行 的成功和失败函数即可。
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);
}
}
我刚开始研究 es6-promises,但我无法理解它。在我的应用程序中,我试图通过 ajax 调用获取 return 数据并继续循环,直到找不到更多数据(本质上是分页)。
这是 ajax 调用,其中 return 是一个承诺对象:
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);
}
});
每次调用 returns 100 条记录,所以我需要继续循环直到 moreData 标志为 false。此外,不确定 promise 方法是否是执行此操作的最有效方法。
$.ajax 已经 returns 为您提供了一个承诺,因此您无需再创建一个,只需传入您想要 运行 的成功和失败函数即可。
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);
}
}