Skip to content

Instantly share code, notes, and snippets.

@WLun001
Last active May 20, 2018 06:06
Show Gist options
  • Save WLun001/bd590c6a8fd86edeaf24d6c307059da8 to your computer and use it in GitHub Desktop.
Save WLun001/bd590c6a8fd86edeaf24d6c307059da8 to your computer and use it in GitHub Desktop.
Javascript HTTP POST request with Promise
//creating promise
// more on https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261
function exampleFunc(value) {
return new Promise((resolve, reject) => {
http.get(option, (res) => {
let body = '';
res.on('data', (d) => {
body += d;
}); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
resolve(response);
});
res.on('error', (error) => {
reject(error);
});
});
});
}
// using promise
var random = exampleFun(value).then((value1) => {
return value1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment