Skip to content

Instantly share code, notes, and snippets.

@evanshortiss
Last active June 9, 2016 19:17
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 evanshortiss/1d8ec1b43f4b129b72fbbd2a372f62b4 to your computer and use it in GitHub Desktop.
Save evanshortiss/1d8ec1b43f4b129b72fbbd2a372f62b4 to your computer and use it in GitHub Desktop.
'use strict';
var Promise = require('bluebird')
, express = require('express');
var app = express();
async function getUsers () {
return new Promise(function (resolve, reject) {
resolve(['jane', 'john']);
});
}
async function getAges () {
return new Promise(function (resolve, reject) {
resolve(['23', '43']);
});
}
async function getData (url) {
var users = await getUsers();
var ages = await getAges();
return {
ages: ages,
users: users
};
}
app.get('/', function (req, res, next) {
getData()
.then((data) => {
res.json(data);
})
.catch(next);
});
app.listen(3001, (err) => {
if (err) {
throw err;
}
console.log('listening on 3001');
});
@MikeyBurkman
Copy link

MikeyBurkman commented Jun 9, 2016

Another way to do this which lets you get both users and ages in parallel is like this. (The error handling is a little annoying though. )

async function getData (url) {
  return Promise.props({
    ages: getAges(),
    users: getUsers()
  });
}
app.get('/', function (req, res, next) {
  let data;
  try {
    data = await getData();
  } catch (err) {
    return next(err);
  }
  res.json(data);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment