我在 js 中调用两个函数,它们通过 ajax 获取数据:
getNumContentTotal(ctx);
getContentAll(ctx);
getNumContentTotal(ctx) 设置 getContentAll(ctx) 所需的 var;
有没有办法在设置我的变量之前不执行第二个函数?
最佳答案
如果您使用的是 jQuery(我假设您使用的是),则返回 ajax 调用在您的 getNumContentTotal()
和 getContentAll()
方法中返回的对象。 jQuery 返回一个类似于 Promise 的对象,允许您以序列化的方式管理回调:
编辑:关于 jQuery promise 的更好文章:Understanding JQuery.Deferred and Promise .
function getNumContentTotal(ctx) {
return $.ajax(...);
}
function getContentAll(ctx) {
return $.ajax(...);
}
var promise = getNumContentTotal(ctx);
promise.pipe(function(data) {
// do something with data
return getContentAll(ctx);
}).done(function(data) {
// do something with data
});
关于javascript - 调用一个函数并在完成之前不继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932443/