0

Why we can't use async with the data function but it is ok with other functions? For example:

export default {
  data: async function () { // not ok
    return {
      item: null,
    }
  },
  beforeMount: async function() { // this is ok
    let result = await axios.get('./data-social.json')
    this.item = result.data
  },
  mounted() {
  },
}

I will get this error:

[Vue warn]: data functions should return an object:

Any ideas?

1 Answer 1

2

Putting async before a function transforms it into a function that returns a Promise. data method must return an object and not a Promise.

async function myFunction () { [code] }

is equivalent to

function myFunction () { 
    return Promise(function (resolve, reject) {
        try {
            resolve((function () { [code] })());
        } catch (error) {
            reject(error);
        }
    });
}

I suggest that you remove the async steatment.

Sign up to request clarification or add additional context in comments.

Comments

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.