0

I'm confused about promises. Why does my variable response_status not change, after axios query. How could I change it?

import axios from 'axios/dist/axios.min.js';

function addOrRemoveFavourite(variation_id, isFav) {
    var response_status = true;

    if (typeof variation_id == 'undefined' || typeof isFav == 'undefined') {
        response_status = false;
    } else {
        let data = {
            product_variation: variation_id
        };
        if (isFav) {
            axios.post('/api/product/remove-from-favourite', data).then(response => {
            }).catch((error) => {
                if (error.response) {
                    response_status = false;
                    alert(error.response.data.message);
                }
            });
        } else {
            axios.post('/api/product/add-to-favourite', data).then(response => {
            }).catch((error) => {
                if (error.response) {
                    alert(error.response.data.message);
                    response_status = false;
                }
            });
        }
    }
    return response_status;
}

response = addOrRemoveFavourite(49, true); //always returns true
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • Hi, Sadriddin, welcome to Stackoverflow. Remember that the purpose is to have questions, try to format your issue as a question and provide as much details as possible :) – versvs Nov 10 '21 at 14:33
  • That is because you're returning the value before the promise is resolved. – Terry Nov 10 '21 at 14:33
  • Promises are asynchronous. Your variable gets changed after the actual response is returned – Suraj Rao Nov 10 '21 at 14:33
  • You cannot get an asynchronous result synchronously. It's like pressing the order button on a pizza site and expecting to have the pizza on your plate the next moment. – trincot Nov 10 '21 at 14:33
  • i would suggest to learn how promises work generally in javascript – bill.gates Nov 10 '21 at 14:34

0 Answers0