DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

Axios return async await

Installing

Package manager
Using npm:

$ npm install axios
Enter fullscreen mode Exit fullscreen mode

Once the package is installed, you can import the library using import or require approach:

const axios = require( 'axios' )
Enter fullscreen mode Exit fullscreen mode

or

import axios from 'axios'
Enter fullscreen mode Exit fullscreen mode

then, create return function

async function myPromise() {

    // return axios( 'https://example.com' )
    return await axios( 'https://example.com' )
        .then( function ( response ) {

            // Process html...
            return ( response )

        } )
        .catch( function ( err ) {

            // Crawling failed...
            return ( err )

        } );

}
Enter fullscreen mode Exit fullscreen mode

And, call the function

(async () => {

    try {

        console.log( await myPromise() )

    } catch ( error ) {

        console.error( `Something went wrong. ${error.message}` );

    }

})();
Enter fullscreen mode Exit fullscreen mode

All Code

/*
    https://www.npmjs.com/package/axios
    https://github.com/axios/axios
    https://axios-http.com/
 */

const axios = require('axios');

async function myPromise() {

    // return axios( 'https://example.com' )
    return await axios( 'https://example.com' )
        .then( function ( response ) {

            // Process html...
            return ( response )

        } )
        .catch( function ( err ) {

            // Crawling failed...
            return ( err )

        } );

}

/* --- */

(async () => {

    try {

        console.log( await myPromise() )

    } catch ( error ) {

        console.error( `Something went wrong. ${error.message}` );

    }

})();
Enter fullscreen mode Exit fullscreen mode

repl.it

Thank you


Top comments (0)