This sample code won't answer any questions you might have about the q library
.
Instead, it just demonstrates how you can use a promise instead of a callback to complete an asynchronous task -- which seems like the underlying goal of your code.
(For more info and examples, you can check out MDN: Promises)
Note that promises are an alternative to callbacks, so an expression like promise(callback)
is not something you'd typically write.
Also, I only looked at q
very briefly, but I think Q.denodeify
might not be the correct method to use for the task you're trying to accomplish.
For suggestions specific to q
, you might also find this answer helpful.
function add(){
// Calling `add` will return a promise that eventually resolves to `7`
// There is no way this particular promise can reject (unlike most promises)
const myPromise = new Promise(function(resolve, reject) {
// The anonymous function we pass to `setTimeout` runs asynchronously
// Whevever it is done, it applies the promise's `resolve` function to `c`
setTimeout(function(){
const
a = 4,
b = 3,
c = a + b;
resolve(c);
}, 200);
});
return myPromise;
}
// `add` returns a promise that always resolves to `7`
// The `.then` method of this promise lets us specify a function that
// does something with the resolved value when it becomes available
add().then(function(resolvedValue){
console.log("addition result: " + resolvedValue);
});