Skip to content

Instantly share code, notes, and snippets.

@1yx
Created January 2, 2017 09:42
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 1yx/23005e7ab0be8e12836e9bb4af827cbd to your computer and use it in GitHub Desktop.
Save 1yx/23005e7ab0be8e12836e9bb4af827cbd to your computer and use it in GitHub Desktop.
test async function after response
'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