How to make a function wait until a callback has been called using node.js
I have a simplified function that looks like this:
function(query) {
myApi.exec('SomeCommand', function(response) {
return response;
});
}
Basically i want it to call myApi.exec
, and return the response that is given in the callback lambda. However, the above code doesn't work and simply returns immediately.
Just for a very hackish attempt, i tried the below which didn't work, but at least you get the idea what i'm trying to achieve:
function(query) {
var r;
myApi.exec('SomeCommand', function(response) {
r = response;
});
while (!r) {}
return r;
}
Basically, what's a good 'node.js/event driven' way of going about this? I want my function to wait until the callback gets called, then return the value that was passed to it.
The "good node.js /event driven" way of doing this is to not wait .
Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:
function(query, callback) {
myApi.exec('SomeCommand', function(response) {
// other stuff here...
// bla bla..
callback(response); // this will "return" your value to the original caller
});
}
So you dont use it like this:
var returnValue = myFunction(query);
But like this:
myFunction(query, function(returnValue) {
// use the return value here instead of like a regular (non-evented) return value
});
check this: https://github.com/luciotato/waitfor-ES6
your code with wait.for: (requires generators, --harmony flag)
function* (query) {
var r = yield wait.for( myApi.exec, 'SomeCommand');
return r;
}
If you don't want to use call back then you can Use "Q" module.
For example:
function getdb() {
var deferred = Q.defer();
MongoClient.connect(databaseUrl, function(err, db) {
if (err) {
console.log("Problem connecting database");
deferred.reject(new Error(err));
} else {
var collection = db.collection("url");
deferred.resolve(collection);
}
});
return deferred.promise;
}
getdb().then(function(collection) {
// This function will be called afte getdb() will be executed.
}).fail(function(err){
// If Error accrued.
});
For more information refer this: https://github.com/kriskowal/q
链接地址: http://www.djcxy.com/p/55684.html