1

I have this action in store

actions: {
    testLogin(context, credentials) {
        const loginService = new FetchClient();
        let d = loginService.post('login', credentials);
        console.log(d);
    },

and this function in another class imported to store

async post(endpoint, params) {
    await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })
        .then(response => {
            return response.json();
        })
        .then( (data) => {
            this.returnData =  data.data;
        })
        .catch(error => {
            console.log(error);
        });
    return this.returnData;
}

And I get Promise {<pending>} which I can extract data from inside the fetch class but can't access data if I'm in the store because it's a Promise not an object. How can I solve this?

2
  • 1
    As async methods return promises you need to work with that. Commented Nov 11, 2020 at 23:11
  • Simply put, an asynchronous result can't be made synchronous without a psychic or time travel - javascript contains neither Commented Nov 12, 2020 at 0:09

3 Answers 3

1

Put the return statement inside the second then block:

async post(endpoint, params) {
    await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })
        .then(response => {
            return response.json();
        })
        .then( (data) => {
            this.returnData =  data.data;
            return this.returnData;
        })
        .catch(error => {
            console.log(error);
        });
}

I would even recommend you use the following code for better legibility:

async post(endpoint, params) {
    const response = await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })

    if (!response.ok) {
        const message = `An error has occured: ${response.status}`;
        throw new Error(message);
    }
    
    const resp_data = await response.json()

    return resp_data.data
}

Then call your method like so:

post(endpoint, params)
    .then(data => {// do something with data})
    .catch(error => {
        error.message; // 'An error has occurred: 404'
    });

refer to this async/await guide

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

1 Comment

Can recommend to always add a try/catch block in order to handle errors better.
0

Can you try:

async testLogin(context, credentials) {
    const loginService = new FetchClient();
    let d = await loginService.post('login', credentials);
    console.log(d);
}

1 Comment

It does log the data but in the js file I use it I find it returned as promise not as data
0
As @Ayudh mentioned, try the following code:

    async post(endpoint, params) {
    try{
        let response = await fetch(this.url + endpoint, {
            'method': 'POST',
            headers: this.headers,
            body: JSON.stringify(params),
        });
        let data = await response.json();
        this.returnData =  data.data;
    }catch(e){
        console.log(e);
    }
    
    return this.returnData;
}

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.