Skip to content

robinslee/async-http-request

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

async-http-request

Simply wrapped request with Promise, so you can use async/await of ES7.

Installation

Using npm:

$ npm i -D async-http-request

Use

"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);
    // ...
}

Basic usage

Resolve with response data

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);
        });
}

Error handling, resolve with Error

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);
}

About

Simply wrap request with Promise, so you can use async/await of ES7.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published