Search code examples
javascriptasynchronousjavascript-import

how to import and export asynchronous function on javascript?


i have this asynchronous function

//example get
  async getDatafromAPINODE(url) {
    try {
      let respond = await axios.get(API_URL_NODE + url, {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + this.state.tokenUser,
        },
      });
      if (respond.status >= 200 && respond.status < 300) {
        console.log("respond Post Data", respond);
      }
      return respond;
    } catch (err) {
      let respond = err;
      console.log("respond Post Data err", err);
      return respond;
    }
  }

how can i make this function export-able ? so i can use in another file with import


Solution

  • ok this what im doing

    //asyncFunction.js
    export const getDatafromAPINODE = async (url, props) => {
      try {
        let respond = await axios.get(API_URL_NODE + url, {
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + props,
          },
        });
        if (respond.status >= 200 && respond.status < 300) {
          console.log("respond Post Data", respond);
        }
        return respond;
      } catch (err) {
        let respond = err;
        console.log("respond Post Data err", err);
        return respond;
      }
    };
    

    then i called using

    import {getDatafromAPINODE} from '../../../helper/asyncFunction'
    

    as you can see im using 2 args url and props, the props will be used for getting the token for my need