1

js project where I need to use await/async for getting data from my API.

My code

        const logsFc = async () => {
          let logs = [];
          for (let i = 0; i < this.data.length; i++) {
            const formData = new FormData();

            const getLogsFc = () => {
              getLogs.request(new URLSearchParams(formData), (response) => {
                if (response.status >= 200 && response.status < 300) {
                  localConsoleLog('getLogs', response);
                  return response.data.data;
                }
              });
            };

            let data = await getLogsFc();
            console.warn(data);
            logs.concat(data);
          }

          return logs;
        };

but logs are returned before getting response.

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        corejs: 3.6,
        modules: false,
      },
    ],
  ],
};

"vue": "^2.6.0"

What am I doing wrong?

4
  • 1
    getLogsFc isn't returning anything. You probably want to put a return before getLogs.request. Commented Sep 5, 2020 at 14:24
  • What is getLogs.request? It doesn't appear to return a promise, so you cannot use await here. Commented Sep 5, 2020 at 14:43
  • @Bergi getLogs.request is axios request Commented Sep 5, 2020 at 14:45
  • 1
    In that case, don't pass a callback but use the promise that it creates Commented Sep 5, 2020 at 14:48

1 Answer 1

1

Don't run the callback of the request just return the response :

 const getLogsFc = async () => {
          let response = await getLogs.request(new URLSearchParams(formData));
            if (response.status >= 200 && response.status < 300) {
                  localConsoleLog('getLogs', response);
                  return response.data.data;
                }
            };

            let data = await getLogsFc();
Sign up to request clarification or add additional context in comments.

2 Comments

Your response here would be a promise and does not have a .status property
you're right i forgot to ad the async/await to the inner function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.