Understand promises before you start using async/await

function getFirstUser() {
return getUsers().then(function(users) {
return users[0].name;
});
}
function getFirstUser() {
return getUsers().then(function(users) {
return users[0].name;
}).catch(function(err) {
return {
name: 'default user'
};
});
}
async function getFirstUser() {
let users = await getUsers();
return users[0].name;
}
async function getFirstUser() {
try {
let users = await getUsers();
return users[0].name;
} catch (err) {
return {
name: 'default user'
};
}
}
let user = await getFirstUser();
let user = getFirstUser();
let foo = await getFoo();
let bar = await getBar();
let [foo, bar] = await* [getFoo(), getBar()];
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
[getFoo(), getBar()]
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
function getFirstUser(callback) {
return getUsers().then(function(users) {
return callback(null, users[0].name);
}).catch(function(err) {
return callback(err);
});
}
function getFirstUser(callback) {
return getUsers().then(function(users) {
return users[0].name;
}).nodeify(callback);
}
function callbackToPromise(method, ...args) {
return new Promise(function(resolve, reject) {
return method(...args, function(err, result) {
return err ? reject(err) : resolve(result);
});
});
}
async function getFirstUser() {
let users = await callbackToPromise(getUsers);
return users[0].name;
}
myApp.endpoint('GET', '/api/firstUser', async function(req, res) {
let firstUser = await getFirstUser();
res.json(firstUser)
});
myApp.endpoint('GET', '/api/firstUser', function(req, res) {
return getFirstUser().then(function(firstUser) {
res.json(firstUser)
});
});
myApp.registerEndpoint('GET', '/api/firstUser', async function(req, res) {
try {
let firstUser = await getFirstUser();
res.json(firstUser)
} catch (err) {
console.error(err);
res.status(500);
}
});

--

--

I write code, sometimes my code works. daniel@bluesuncorp.co.uk

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store