1

Here's my code

main.js

// main.js

const calc = require('./calc');

const calcInfo = calc.getCalcInfo();
console.log('calcInfo:', calcInfo); // I expect wait until response data

and calc.js

// calc.js

import axios from 'axios';

const getCalcInfo = async () => {
  let resultData = await axios.post('/api/logis/getCalcInfo', {});
  console.log('getCalcInfo', resultData);
  return resultData;
}

export {
  getCalcInfo,
}

result log

calcInfo: Promise {<pending>}__proto__: Promise[[PromiseStatus]]: "fulfilled"[[PromiseValue]]: Object
calc.js:6 getCalcInfo {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}

I expected log "calcInfo" will show axios responsed data. but that's return Promise.

Is there a solution for this issue?


EDIT: thanks for reply! but i'm still have a question.

this is a modified code. same main.js and calc.js

const getCalcInfo = () => {
  axios.post('/api/logis/getCalcInfo', {})
  .then((result) => {
    return result;
  });
}

result here:

calcInfo: undefined

so I'm not using async(but axios maybe using). but call getCalcInfo's result is undefined.

why does it work like this?

rodpold
  • 156
  • 6
  • 1
    It's `await calc.getCalcInfo();` – amedina Aug 19 '20 at 12:10
  • Yup, like the comment above said, you need to `await` since you are calling an `async` function which returns a `Promise` – Liew Xun Aug 19 '20 at 12:12
  • 1
    Do `resultData.data` – Kunal Mukherjee Aug 19 '20 at 12:12
  • An `async` function _always_ returns a Promise. If you write `return 3` at the end, it won't return the number 3, but a _Promise resolving with the number 3_. That's why you need to await it : `const calcInfo = calc.getCalcInfo()` will be a pending promise, but `const calcInfo = await calc.getCalcInfo()` will be `3`. – Jeremy Thille Aug 19 '20 at 13:03
  • Write a new question if you have another problem. That one should remain closed as a duplicate. – pptaszni Aug 20 '20 at 11:17

0 Answers0