Home > Software engineering >  how to wrap axios function and let parent to wait?
how to wrap axios function and let parent to wait?

Time:06-20

here's I've my axios function wrapped within a custom function:

async function getOrder(orderId) {
    // ...

    await axios({
        method: 'post',
        url: endpoint   "/mymethod",
        data: request
    }).then(function (response) {
        var data = response.data.result;
        return data;
    }).catch(function (error) {
        return { "error": error };
    });
}

but if than i call that function:

router.get('/getOrder/:id', (req, res) => {
    let result = getOrder(req.params.id);
    res.json(result);
})

it returns nothing (since its async and don't wait the .then()).

what's the best way to wrap axios/async function and call from outside?

CodePudding user response:

I think you're missing await in your codes:

router.get('/getOrder/:id', async (req, res) => {
    let result = await getOrder(req.params.id);
    res.json(result);
})

====================

[New Update] for me in API function:

async getOrder(orderId) {
    try {
      const response = await axios.post(endpoint   "/mymethod")
      return response.data
    } catch (error) {
      return { "error": error }
    }
  }

and get the result:

router.get('/getOrder/:id', async (req, res) => {
    let result = await getOrder(req.params.id);
    res.json(result);
})

===========

[New Update2] here is my sample async/await function with axios

const axios = require("axios")

async function getOrder(orderId) {
  try {
    const response = await axios.get("http://google.com")
    return response.data
  } catch (error) {
    return { "error": error }
  }
}


async function main() {
  let result = await getOrder();
  console.log(result, "@@")
}
main()

====================

[New Update3] new Promise with axios:

const axios = require("axios")

async function getOrder(orderId) {
  // try {
  //   const response = await axios.get("http://google.com")
  //   return response.data
  // } catch (error) {
  //   return { "error": error }
  // }
  return await new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: "http://google.com"
    }).then(function (response) {
      var data = response.data
      resolve(data)
    }).catch(function (error) {
      reject({ "error": error })
    });
  })
}


async function main() {
  let result = await getOrder();
  console.log(result, "@@")
}
main()

CodePudding user response:

I think you are missing an await so you do not return a promise but wait for the result of getOrder to be passed in res.json :

router.get('/getOrder/:id', async (req, res) => {
        let result = await getOrder(req.params.id);
        res.json(result);
    })
  • Related