문제

I have an array of properties that are children of an object that will need to be persisted via AJAX calls to a database. However, the way the API is working right now (this is highly unlikely to change) I cannot send the strings in a batch and if I send them using a simple loop they will each overwrite each other. So I need to process additions and subtractions as a FIFO queue.

I'm just trying to verify if my thinking is correct in that processing the AJAX call back interrupts processing of the actions that add/subtract properties to the queue.

Code (using jQuery $.ajax for shorthand):

var queue = [],
    processing = false;

function processQueue() {
    if(queue.length <= 0) {
        processing = false;
        return;
    }

    if(processing) {
        return;
    }

    processing = true;
    var cmd = queue.unshift();

    $.post(cmd.location, cmd.payload, function handleSuccess() {
        processing = false;
        processQueue();
    });
}

function addToQueue(url, payload) {
    queue.push({ location: url, payload: payload });
    processQueue();
}

Primarily I'm concerned about which processQueue(); call gets made first after the initial one. Assuming that I've added several things to the queue and then called processQueue();. I believe that if a call to handleSuccess(); is made in the middle of a call to addToQueue() that the call to processQueue() from addToQueue() would result in an early return since processing == true. However, I'm not certain enough of this.

Am I correct in my thinking?

도움이 되었습니까?

해결책

processing the AJAX call back interrupts processing of the actions that add/subtract properties to the queue.

No. JavaScript is singlethreaded, no race conditions can occur in synchronous code. The ajax callback is queued in the event queue, and will get scheduled to be executed after any currently-executing code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top