Skip to content

Instantly share code, notes, and snippets.

@seansullivan
Created March 6, 2014 03:25
Show Gist options
  • Save seansullivan/9381705 to your computer and use it in GitHub Desktop.
Save seansullivan/9381705 to your computer and use it in GitHub Desktop.
Q Promise Chain that deals with sync and async functions.
var q = require('q');
var counter = 0,
current = counter,
syncFunc = function (result) {
current = counter++;
console.log('in sync func '+current);
return 'from func '+current;
},
asyncFunc = function (result, callback) {
current = counter++;
setTimeout(function () {
console.log('in async func '+current);
callback(null, 'from func '+current);
}, 0);
},
// need to convert async function into one that will return a promise
denodeifiedAsyncFunc = q.denodeify(asyncFunc);
q.fcall(syncFunc)
.then(
function (result) {
return denodeifiedAsyncFunc(result);
}
)
.then(
function (result) {
return q.fcall(syncFunc, result);
}
)
.then(
function (result) {
return q.fcall(syncFunc, result);
}
)
.catch(function (err) {
console.log(err.stack);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment