Last active
May 20, 2018 06:06
-
-
Save WLun001/bd590c6a8fd86edeaf24d6c307059da8 to your computer and use it in GitHub Desktop.
Javascript HTTP POST request with Promise
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
//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