避免异步:false;在jQuery AJAX中的一个函数 [英] Avoiding async: false; in jQuery AJAX within a function

查看:62
本文介绍了避免异步:false;在jQuery AJAX中的一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的一些伪代码(我通常使用 async:false; ):

Here's some pseudo code that I'm working with (and where'd I'd typically use async: false;):

function getData(){
    var obj = {};
    if(!settings.data){
        $.ajax({
            url: '/someendpoint',
            async: false,
            success: function(data){
                obj = data;
            }
        });
    } else {
        obj = settings.data;
    }
    return obj;
}

所以我们有一个返回一个对象的函数。现在,如果我们已经有了一些数据,我们只需分配这些数据,但如果不这样做,我们需要从服务器请求数据。是时候使用 async:false ?因为在返回obj之前我们需要暂停执行以获取数据?

So we have a function that returns an object. Now if we already have some data, we just assign this data, but if we don't, we need to request the data from the server. A time to use async: false? Because we need to halt execution as to grab the data before we return the obj?

我一次又一次地处理这个概念,诉诸 async:false 大部分时间。有人可以概述一个更好的方法吗?

I deal with this concept time and time again, resorting to async: false most times. Can someone outline a better approach please?

推荐答案

使用简单的回调机制

function getData(callback){
    var obj = {};
    if(!settings.data){
        $.ajax({
            url: '/someendpoint',
            success: function(data){
                callback(data)
            }
        });
    } else {
        callback(settings.data)
    }
}

getData(function(data){
    //do things which depends on data
})

这篇关于避免异步:false;在jQuery AJAX中的一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆