简体   繁体   中英

Javascript Asynchronous Order

My question is specific to Javascript and asynchronous operations. I am building a Node.js API for interacting with a database (OrientDB) and I am using a Node-orient package providing basic connectivity functions. Some of these functions look like the following:

db.delete("...")
db.insert("...")
etc.

Each of them return a promise that can be used to act on the results:

db.insert("...").then(function(records) {
    res.send(records);
});

My goal is to execute two delete statements (order does not matter) and then execute an insert statement (must happen after the delete statements else I will end up deleting the inserted record). Can I simply write the following:

db.delete("...");
db.delete("...");
db.insert("...");

In other words, is the order of aynchronous operations in a single-threaded environment like Javascript maintained??? or do I need to create some sort of promise:

var promise = new Promise(function(resolve, reject) {

    db.delete("thing to delete").then(handleFinish, reject);
    db.delete("other thing to delete").then(handleFinish, reject);

    var finished = false;

    function handleFinish() {
        if(finished){
            resolve();
        }
        else {
            finished = true;
        }
    }
});

and then

promise.then(function(){
    db.insert("...");
});

Or is there some better alternative to accomplishing this? I'm new to Node and new to asynch programming.

This can be achieved with promises, for which many modules exist. Here's an example with promise

var Promise = require('promise');

Promise.all([
  db.delete(...),
  db.delete(...)
]).then(function(result) {
  db.insert(...);
});

When you're dealing with callbacks, you can use a control flow module such as async

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