Simply wrapped request with Promise, so you can use async/await of ES7.
Using npm:
$ npm i -D async-http-request
"use strict";
const asyncRequest = require("async-http-request");
const url = "http://www.google.com";
run();
// await must be inside a async function
async function run() {
await asyncRequest(url);
// ...
}
Note, await could only be used in async function. See async & await
(async function() {
// Resolved with response data
let body = await asyncRequest(url);
console.log(body);
})();
Resolve with response object, instance of http.IncomingMessage
const resolveWithResponse = true;
async function run() {
// Resolved with response object
let response = await asyncRequest({
url,
resolveWithResponse
});
console.log(response.statusCode);
console.log(response.headers['content-type']);
}
Resolve with raw object as same as request returned
With this object, you can use all methods that doc shows
const fs = require("fs");
const resolveWithRequest = true;
async function run() {
// Resolved with response object
let oReq = await asyncRequest({
url,
resolveWithRequest
});
console.log(oReq);
// Sample 1, pipe stream
oReq.pipe(fs.createWriteStream("foo.txt"));
// Sample 2, events
oReq
.on("response", function(resp) {
console.log(resp.statusCode);
})
.on("error", function(err) {
console.log(err);
});
}
async function run() {
// Something wrong like net work issue
let err = await asyncRequest(url);
console.log(err);
}
Convenience methods of request
async function run() {
// Something wrong like net work issue
let body_get = await asyncRequest.get(url);
console.log(body_get);
let body_post = await asyncRequest.post({
url,
form: {
name: "Foo"
}
});
console.log(body_post);
}