Last active
January 23, 2017 08:03
-
-
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
This file contains 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
'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