简体   繁体   中英

Detect running javascript workers

I am writing a javascript HTML5 phonegap application. I am using SQLite to store data. For the sake of performance, i am undertaking database inserts asynchronously ie I do not need to call the next operation at the callback of the previous Database operation. Internally, i believe javascript is creating a worker for each operation hence multi-threading so to speak.

The problem now is , How do i know that all workers have completed their tasks? eg, in order to tell the user that all data has been saved?

If I understand your request correctly, you are queueing up DB inserts to run asynchronously and you want to be able to check back at a later time to see if all the requests are finished. I would do something like this:

function asyncTask() {
        //
        // Do real work here
        //
        runningTasks--
}


//in your init section, setup a global variable to track number of tasks    
runningTasks = 0

//when you need to create a new task, increment the counter
runningTasks++;
setTimeout (asyncTask,1);



if (runningTasks > 0) {
    //something still running
} else {
    //all tasks are done.
}

In another language you would need to worry about race conditions when testing and setting the runningTasks varaible, but AFAIK, Javascript is only implemented as single threaded so you don't need to worry about that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM