Created
January 2, 2017 09:42
-
-
Save 1yx/23005e7ab0be8e12836e9bb4af827cbd to your computer and use it in GitHub Desktop.
test async function after response
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 Promise = require('bluebird'); | |
const app = express(); | |
const delayAndSometimesThrowError = (second) => { | |
const deferred = Promise.pending(); | |
setTimeout(function() { | |
if (Math.random() > 0.5) { | |
deferred.resolve('good luck'); | |
} else { | |
deferred.reject(new Error('bad luck(' + second + ')')); | |
} | |
}, second * 1000); | |
return deferred.promise; | |
} | |
app.get('/', (req, res, next) => { | |
console.log('request at:\t' + new Date()); | |
delayAndSometimesThrowError(1).then((text) => { | |
console.log('response at:\t' + new Date()); | |
return res.send(text); | |
}).catch((err) => { | |
res.send(err.message); | |
}).then(() => { | |
return delayAndSometimesThrowError(2); | |
}).then(() => { | |
console.log('finish at:\t' + new Date()); | |
return; | |
}).catch((err) => { | |
console.error(err); | |
}) | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment