Skip to content

Instantly share code, notes, and snippets.

@laterbreh
Last active January 23, 2017 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laterbreh/c9b6bb03178ab17f25a36505cc7f4c5f to your computer and use it in GitHub Desktop.
Save laterbreh/c9b6bb03178ab17f25a36505cc7f4c5f to your computer and use it in GitHub Desktop.
Using Bluebird's Promise.Coroutine to write asynchronous code "synchronously" in Node 7.4.0 and Express 4
'use strict'
const express = require('express');
const app = express();
const Promise = require('bluebird');
const {coroutine: co} = require('bluebird'); //Alias coroutine
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
app.get('/', (req, res)=>{
console.log('hit')
//Create the self invoking function
co(function* () {
try {
let _first = yield first();
let _second = yield second();
let _final = yield putittogether(_first, _second);
//Respond
res.json(_final);
} catch(e) {
//If there was a rejection we will catch it here.
res.json(e);
}
})();
})
function first() {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(1);
}, 2000)
})
}
function second() {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(2);
}, 1)
})
}
function putittogether(first, second) {
return new Promise((resolve, reject)=>{
resolve(first + second);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment