Created
December 7, 2017 10:56
-
-
Save cnayan/f0c47f6718856b95f726f42cb0a06f51 to your computer and use it in GitHub Desktop.
JavaScript "request" callbacks transformed to async/await
This file contains hidden or 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 requestAsync = require('./requestAsync'); | |
let options = { | |
uri: 'http://localhost:3000/endpoint', | |
method: 'POST', | |
json: {} // your data | |
}; | |
async function main() { | |
let result = await requestAsync(options); | |
// rest of the code using result | |
} | |
main(); |
This file contains hidden or 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 request = require('request'); | |
module.exports = function requestAsync(options) { | |
return new Promise((resolve, reject) => { | |
try { | |
request(options, (err, res, body) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve({ res, body }); | |
} | |
}); | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment