Question

I want to use NodeJS to read 60k records from a MySQL database and write them to a ArangoDB database. I will later use ArangoDB's aggregation features etc. to process my dataset.

Coming from PHP, where a script usually runs synchronous, and because I believe it makes sense here, my initial (naive) try was to make my NodeJS script run sync too. However, it doesn't work as expected:

I print to console, call a function via .sync() to connect to ArangoDB server and print all existing databases, then print to console again. But everything below the sync call to my ArangoDB function is completely ignored (does not print to console again, nor does it seem to execute anything else here).

What am I overlooking? Does .done() in the function called via .sync() cause trouble?

var mysql = require('node-mysql');
var arango = require('arangojs');
//var sync = require('node-sync'); // Wrong one!
var sync = require('sync');


function test_arango_query() {
    var db = arango.Connection("http://localhost:8529");
    db.database.list().done(function(res) {
        console.log("Databases: %j", res);
    });
    return "something?";
}

sync(function() {
    console.log("sync?");
    var result = test_arango_query.sync();
    console.log("done."); // DOES NOT PRINT, NEVER EXECUTED?!
    return result;

}, function(err, result) {
    if (err) console.error(err);
    console.log(result);
});
Était-ce utile?

La solution

Your function test_arango_query doesn't use a callback. sync only works with functions that use a callback. It needs to know when the data is ready to return it from .sync(), if your function never calls the callback, then sync can't ever return a result.

Update your function to call a callback function when you want it to return:

function test_arango_query(callback) {
    var db = arango.Connection("http://localhost:8529");
    db.database.list().done(function(res) {
        console.log("Databases: %j", res);
        callback('something');
    });
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top