Skip to content

Instantly share code, notes, and snippets.

@sudosoul
Last active May 16, 2018 04:03
Show Gist options
  • Save sudosoul/2294b16c0826da4555da84faee54fb94 to your computer and use it in GitHub Desktop.
Save sudosoul/2294b16c0826da4555da84faee54fb94 to your computer and use it in GitHub Desktop.
async-vs-promise-request.
const res = await saveToCache(1, 1); // Will `res` resolve with the response from the request made in the below function?
async function saveToCache(numberOfPills, numberOfPermutations) {
Request({
url : process.env.cacheUrl,
method : 'POST',
body : {pills: numberOfPills.toString(), permutations: numberOfPermutations.toString()}, // Even though these values are defined as Numbers in Dynamo, we have to pass them as a string in the request body for the API GW -> Dynamo proxy mapping to work.
headers : {'Content-Type': 'application/json'}
}, (err, res, body) => {
if (err) throw new Error('Error: Internal Error Making POST Request to Cache Service - ' +err);
if (res.statusCode !== 200) throw new Error('Error: POST Request to Cache Service failed - ' +res);
return res;
});
}
// In past, I've written like so...
function saveToCache(numberOfPills, numberOfPermutations) {
return new Promise((resolve, reject) => {
Request({
url : process.env.cacheUrl,
method : 'POST',
body : {pills: numberOfPills.toString(), permutations: numberOfPermutations.toString()}, // Even though these values are defined as Numbers in Dynamo, we have to pass them as a string in the request body for the API GW -> Dynamo proxy mapping to work.
headers : {'Content-Type': 'application/json'}
}, (err, res, body) => {
if (err) throw new Error('Error: Internal Error Making POST Request to Cache Service - ' +err);
if (res.statusCode !== 200) throw new Error('Error: POST Request to Cache Service failed - ' +res);
resolve(res);
});
});
}
// So something like this would work...
saveToCache(1,1)
.then(res => {
console.log('Got the response! - ', res);
}).catch(e => {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment