Created
March 6, 2014 03:25
-
-
Save seansullivan/9381705 to your computer and use it in GitHub Desktop.
Q Promise Chain that deals with sync and async functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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