-
Notifications
You must be signed in to change notification settings - Fork 156
JavaScript: Using Promise, async and await with HTTPRequest
Günter Obiltschnig edited this page Jan 17, 2019
·
1 revision
Here is a small JavaScript snippet that shows how to use Promise
objects, as well as async
and await
with HTTPRequest
objects.
var net = require('net');
function download(uri)
{
return new Promise((resolve, reject) => {
var request = new net.HTTPRequest('GET', uri);
var response = request.send(result => {
if (result.error)
reject(result.error);
else
resolve(result.response);
});
});
}
download('https://macchina.io').then(response => {
console.log('%d %s', response.status, response.reason);
console.log(response.contentType);
console.log(response.content);
});
const result = (async () => {
try
{
var response = await download('https://macchina.io');
console.log('%d %s', response.status, response.reason);
console.log(response.contentType);
console.log(response.content);
}
catch (err)
{
console.log(err)
}
})();