按照正确的顺序执行javascript Ajax和非Ajax调用

按照正确的顺序执行javascript Ajax和非Ajax调用,javascript,jquery,ajax,notifications,Javascript,Jquery,Ajax,Notifications,我有一个执行函数的for循环。此函数根据变量执行ajax请求,或者只是附加到HTML 代码如下所示: var index = 0; for (index = 0; index < currentAmountOfUnreadNotifications; ++index) { var currNotification = response.notifications[index]; createAndAppendNotification(notification

我有一个执行函数的for循环。此函数根据变量执行ajax请求,或者只是附加到HTML

代码如下所示:

 var index = 0;
 for (index = 0; index < currentAmountOfUnreadNotifications; ++index) {
       var currNotification = response.notifications[index];
       createAndAppendNotification(notificationHtmlElement, baseUrl, localBaseUrl, currNotification);
 }

function createAndAppendNotification(ele, baseUrl, localBaseUrl, notification) {
    var notificationId = notification.notification_id;
    var subjectLangKey = notification.subject_js_lang_key;
    var messageLangKey = notification.message_js_lang_key;
    var urlLangKey = notification.cta_url_js_lang_key;
    var urlTranslation = res[urlLangKey];
    if (localBaseUrl) {
        var fullCtaUrl = localBaseUrl + "/" + urlTranslation;
    } else {
        var fullCtaUrl = baseUrl + "/" + urlTranslation;
    }
    var fromUserId = notification.from_user_id;
    var fromUserAuthLevel = notification.from_user_auth_level;
    var currLang = $('html').attr('lang');
    moment.locale(currLang);
    var timeSince = moment.utc(notification.timestamp_inserted_utc).fromNow();

    //If the from_user_id is filled in, we need to perform an additional AJAX request in order to retrieve the username and the profile picture/logo.
    if (fromUserId) {
        $.ajax({
            type: 'post',
            cache: false,
            url: baseUrl + '/notification/ajaxmethods/getUserInfoForNotification',
            data: {
                'user_id': fromUserId,
                'auth_level': fromUserAuthLevel
            },
            dataType: 'json',
            success: function(response){
                var subjectTranslation = res[subjectLangKey].format(response.name);
                var messageTranslation = res[messageLangKey].format(response.name);

                var notificationHtml = '<a class="notification-cta" href="'+fullCtaUrl+'" data-notification-id="'+notificationId+'"><div class="media single-notification"><div class="media-left align-self-center"><span class="avatar avatar-online"><img src="'+response.picture+'" alt="avatar"></span></div><div class="media-body"><h6 class="media-heading yellow darken-3">'+subjectTranslation+'</h6><p class="notification-text font-small-3 text-muted">'+messageTranslation+'</p><small class="float-left"><time class="media-meta text-muted">'+timeSince+'</time></small><small class="float-right"><span class="media-meta cursor-pointer blue text-muted notification-mark-read" data-notification-id="'+notificationId+'">'+res.MarkAsRead+'</span></small></div></div></a>';

                ele.append(notificationHtml);
            }
        });
    } else {
        var subjectTranslation = res[subjectLangKey];
        var messageTranslation = res[messageLangKey];
        var iconClass;
        switch(notification.type) {
            case '0':
                iconClass = "ft-info";
                break;
            case '1':
                iconClass = "ft-check-circle";
                break;
            case '2':
                iconClass = "ft-info";
                break;
            case '3':
                iconClass = "ft-alert-triangle";
                break;
            case '4':
                iconClass = "ft-x-circle";
                break;
            default:
                iconClass = "";
            // code block
        }
        var notificationHtml = '<a class="notification-cta" href="'+fullCtaUrl+'" data-notification-id="'+notificationId+'"><div class="media single-notification"><div class="media-left align-self-center"><i class="'+iconClass+' icon-bg-circle bg-yellow bg-darken-3"></i></div><div class="media-body"><h6 class="media-heading yellow darken-3">'+subjectTranslation+'</h6><p class="notification-text font-small-3 text-muted">'+messageTranslation+'</p><small class="float-left"><time class="media-meta text-muted">'+timeSince+'</time></small><small class="float-right"><span class="media-meta cursor-pointer blue text-muted notification-mark-read" data-notification-id="'+notificationId+'">'+res.MarkAsRead+'</span></small></div></div></a>';
        ele.append(notificationHtml);
    }
}
问题是AJAX请求将比其他请求完成得晚,如果对于exmaple来说,最新的通知是需要AJAX请求的通知,那么它将在下拉列表中最后一个追加,而不是第一个追加


关于这一点的所有解决方案都需要一个AJAX调用,在我的代码中,它有时使用AJAX,有时不使用

Ajax调用是异步的,而附加到HTML的调用是同步的,这导致了您描述的问题。但是,如果使用async/await重新构造代码,则可以强制脚本按顺序完成每个操作,无论是同步HTML追加还是异步ajax调用

您的代码如下所示:

 var index = 0;
 for (index = 0; index < currentAmountOfUnreadNotifications; ++index) {
       var currNotification = response.notifications[index];
       createAndAppendNotification(notificationHtmlElement, baseUrl, localBaseUrl, currNotification);
 }

function createAndAppendNotification(ele, baseUrl, localBaseUrl, notification) {
    var notificationId = notification.notification_id;
    var subjectLangKey = notification.subject_js_lang_key;
    var messageLangKey = notification.message_js_lang_key;
    var urlLangKey = notification.cta_url_js_lang_key;
    var urlTranslation = res[urlLangKey];
    if (localBaseUrl) {
        var fullCtaUrl = localBaseUrl + "/" + urlTranslation;
    } else {
        var fullCtaUrl = baseUrl + "/" + urlTranslation;
    }
    var fromUserId = notification.from_user_id;
    var fromUserAuthLevel = notification.from_user_auth_level;
    var currLang = $('html').attr('lang');
    moment.locale(currLang);
    var timeSince = moment.utc(notification.timestamp_inserted_utc).fromNow();

    //If the from_user_id is filled in, we need to perform an additional AJAX request in order to retrieve the username and the profile picture/logo.
    if (fromUserId) {
        $.ajax({
            type: 'post',
            cache: false,
            url: baseUrl + '/notification/ajaxmethods/getUserInfoForNotification',
            data: {
                'user_id': fromUserId,
                'auth_level': fromUserAuthLevel
            },
            dataType: 'json',
            success: function(response){
                var subjectTranslation = res[subjectLangKey].format(response.name);
                var messageTranslation = res[messageLangKey].format(response.name);

                var notificationHtml = '<a class="notification-cta" href="'+fullCtaUrl+'" data-notification-id="'+notificationId+'"><div class="media single-notification"><div class="media-left align-self-center"><span class="avatar avatar-online"><img src="'+response.picture+'" alt="avatar"></span></div><div class="media-body"><h6 class="media-heading yellow darken-3">'+subjectTranslation+'</h6><p class="notification-text font-small-3 text-muted">'+messageTranslation+'</p><small class="float-left"><time class="media-meta text-muted">'+timeSince+'</time></small><small class="float-right"><span class="media-meta cursor-pointer blue text-muted notification-mark-read" data-notification-id="'+notificationId+'">'+res.MarkAsRead+'</span></small></div></div></a>';

                ele.append(notificationHtml);
            }
        });
    } else {
        var subjectTranslation = res[subjectLangKey];
        var messageTranslation = res[messageLangKey];
        var iconClass;
        switch(notification.type) {
            case '0':
                iconClass = "ft-info";
                break;
            case '1':
                iconClass = "ft-check-circle";
                break;
            case '2':
                iconClass = "ft-info";
                break;
            case '3':
                iconClass = "ft-alert-triangle";
                break;
            case '4':
                iconClass = "ft-x-circle";
                break;
            default:
                iconClass = "";
            // code block
        }
        var notificationHtml = '<a class="notification-cta" href="'+fullCtaUrl+'" data-notification-id="'+notificationId+'"><div class="media single-notification"><div class="media-left align-self-center"><i class="'+iconClass+' icon-bg-circle bg-yellow bg-darken-3"></i></div><div class="media-body"><h6 class="media-heading yellow darken-3">'+subjectTranslation+'</h6><p class="notification-text font-small-3 text-muted">'+messageTranslation+'</p><small class="float-left"><time class="media-meta text-muted">'+timeSince+'</time></small><small class="float-right"><span class="media-meta cursor-pointer blue text-muted notification-mark-read" data-notification-id="'+notificationId+'">'+res.MarkAsRead+'</span></small></div></div></a>';
        ele.append(notificationHtml);
    }
}
对于let指数=0;索引如果您既不知道fetch也不知道async/await,那么是时候使用它们了!jquery发出的这个ajax调用在2019年有点过时了

没有回答你的问题,但我认为如果你使用React或Vue这样的框架,可以很容易地将JS逻辑与HTML解耦,那么你的生活会简化很多。你的代码调试起来就像一场噩梦^^为什么你不能映射所有用户ID并发送一次ajax请求,然后编写逻辑来处理响应,然后执行非ajax请求块?我建议你在编写代码时不要担心什么可以在旧版浏览器上工作,而是使用像babel这样的很棒的工具来构建多个目标,这些工具可以自动用polyfills替换所有不受支持的代码