I need some help on syntax with node.js promises
. In readme for node.js
module called q https://github.com/kriskowal/q is written something I don't understand.
Why do they always write return
before promise
?
return Q.fcall(eventualAdd, 2, 2);
How do I make an asynchronous function with callback into function that returns promise
? I try
function doThis(a,b, callback) { var result = a+ b; setTimeout( callback, 2000, result);}
Q.ncall(doThis, 2,3).then( function(result) { alert(result); });
I think after 2000 it must alert with 5 but nothing happens.
The reason is that in that case they want to return the promise to the caller of the current function.
I've done this in my own program and it is done thus:
Q.ncall([function], [this], [arguments,...])
is this
.Secondly note that the arguments to the callback given by Q.ncall
to the given function are the same as all other node.js callbacks (error, result)
thus the need to give the callback null
as the error on success.
var Q = require('q');
function doThis(a,b, callback) {
var result = a + b;
setTimeout(function () { callback(null, result) }, 2000);
}
Q.ncall(doThis, null, 2, 3).then(function(result) { console.error(result); });
This code works as you describe; note the differences.