lundi 24 octobre 2016

How to achieve sequential execution of code containing both testing and asynchronous function calls

I want to execute four blocks of code sequentially and conduct test during this sequential execution. The challenge is that the blocks contain calls of asynchronous functions.

I cannot seem to wrap my head around promises to use them properly and I just seem stuck after spending several hours on the block of code.

// Store current log of drone visits for DJI Phantom 4
db.query("SELECT COUNT(drone_id) FROM Drone_Visits WHERE drone_id = 2;", function(err, rows) {
    if (err) {
        console.log(err);
    }
    else {
        current_drone_visits = rows[0]['COUNT(drone_id)'];                  
    }
});

it("should return status 200 (OK) when requesting route for this function", function(done) {
    request.get("/product/DJI/Phantom_4").query({brand: dji_brand, model: dji_model}).end(function(err, res) {
        assert.equal(res.status, 200);  
        done();
    }); 
});


db.query("SELECT COUNT(drone_id) FROM Drone_Visits WHERE drone_id = 2;", function(err, rows) {
    if (err) {
        console.log(err);
    }
    else {
        updated_drone_visits = rows[0]['COUNT(drone_id)'];                  
    }
});

it("should increment the value of drones visited in the database", function(done) {
    console.log("A - " + current_drone_visits);
    console.log("B - " + updated_drone_visits);
    assert.equal(current_drone_visits + 1, updated_drone_visits);
    done();
});

What should I do here if I want to chain my callbacks such that they execute only after the previous function has finished?

Aucun commentaire:

Enregistrer un commentaire