Last active
May 16, 2018 04:03
-
-
Save sudosoul/2294b16c0826da4555da84faee54fb94 to your computer and use it in GitHub Desktop.
async-vs-promise-request.
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
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