Return Promise from Axios?

axios return data from promise
axios promise
axios promise example
axios post
axios return promise pending
axios promise all
axios interceptors
axios await

I am wondering how do I return a promise form Axios? I am not sure if I need to use an Interceptors?

I have this code right now

export function fetchStorage() {
    return function (dispatch) {
      return new Promise(function(resolve, reject) {
        if (1 === 1) {
          resolve('it works!');
        } else {
          reject(':(');
        }
      });
    };
}

and

this.props.fetchStorage().then(function() {
           console.log('then');
        });

Now say I want to change the fetchStorage to do something via ajax and I would have it like

 var instance = axios.create({
            baseURL: 'http://localhost:54690/api',
            timeout: 2000,

        });

        instance.get('/Storage/Get')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });

how do I return the promise instead of doing it here?

Edit

Just for clarification why I am doing this I have something like this

  componentWillMount() {
        this.props.setPreLoader(true);
        this.props.fetchStorage().then(function() {
           this.props.setPreLoader(false);
        });
    }

export function fetchStorage() {
    return function (dispatch) {
        return new Promise(function (resolve, reject) {
            axiosInstant.get('/Storage/Get')
                .then(function (response) {
                    let payload = response.data;
                    console.log(payload);
                    dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    };
}

There must be a better way but you could

export async function fetchStorage() {
    return async function (dispatch) {
        try {
            const { data } = await axiosInstant.get('/Storage/Get')
            dispatch({ type: actions.FETCH_STORAGE, payload: { storages: data } })
            return data
        } catch (e) {
            console.error(e)
        }
    }
}

Then you have to use fetchStorage as follows

this.props.fetchStorage().then(async function(response) {
    let payload = await response()
});

Returning data from Axios API, The axios library creates a Promise() object. Promise is a built-in object in JavaScript ES6. When this object is instantiated using the new keyword, it takes a function as an argument. This single function in turn takes two arguments, each of which are also functions — resolve and reject. One of Axios’ more interesting features is its ability to make multiple requests in parallel by passing an array of arguments to the axios.all() method. This method returns a single promise object that resolves only when all arguments passed as an array have resolved. Here’s a simple example:

Axios is promise based, so you don't need to wrap it in Promise, you can do something like this, and axiosInstance.[post|put|get| end etc.] methods will return promise.

export function fetchStorage() {
    return function (dispatch) {
       return axiosInstant.get('/Storage/Get')
                .then(function (response) {
                    let payload = response.data;
                    console.log(payload);
                    dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
                })
                .catch(function (error) {
                    console.log(error);
                });
    };
}

axios.AxiosPromise.then JavaScript and Node.js code examples , upload (data) { return new Promise((resolve, reject) => { Vue.axios.post('/image', data, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response� Axios.get () returns a promise, it is async ofcourse. That means your getSrc () is also async so it cannot just return a value when called. That value does not exist yet at the moment of calling it! So, your code looks ok, your getSrc () will return a promise which you can manipulate later.

See sample:

 return new Promise(function (resolve, reject) {
    var instance = axios.create({
        baseURL: 'http://localhost:54690/api',
        timeout: 2000,
    });
    instance.get('/Storage/Get')
        .then(function (response) {
            if(1 === 1)
            resolve(response);
        })
        .catch(function (error) {
            reject(error);
        });

 });

Introducing Axios, a Popular, Promise-based HTTP Client, Once you make a request, Axios returns a promise that will resolve to either a response object or an error object. Axios is a promise-based HTTP client that works in the browser and in a node.js environment. It provides a single API for dealing with XMLHttpRequests and node’s HTTP interface. Besides that, it…

How can I use the data of axios's response outside?, Chuoke ChungYoung since axios returns a promise object, return the axios.get() promise instead of passing the data to src variable, and then� Axios tutorial shows how to generage requests in JavaScript using Axios client library. Axios is a promise based HTTP client for the browser and Node.js.

How to return Promise.resolve in Interceptors on error ? � Issue , How to return Promise resolve, when I have status 403 ? axios.interceptors. response.use(function (response) { return response; }, function� export const actions = { async getIncidents() { let res = await this.$axios.get('/incidents') return res; } } Here, we created the action called getIncidents which is an async function, then we await a response from the server and return this response.

Axios is not resolving its promise and updating the state variables in , what is the correct way to resolve axios promise for post method ??? Because setState(prevState => { return { authentication: response.data. The one thing you need to know about async functions is that; they always returns a promise. In the case where we explicitly return something that is not a promise, like above, the return value is automatically wrapped into a resolved promise with the resolved value being the non-promise.

Comments
  • Why not return instance.get('/Storage/Get') am I missing something here?
  • well I am using redux pattern so I need to send out the dispatch and if I just return like you have, then I always have to remember to send out that dispatch everytime I use that function.
  • @chobo2 i don't understand why you aren't returning the promise that axios is already giving you.
  • My edit is now based on JokerManh answer. I hope I don't need to wrap it around with that promise but I am unsure right now how to return the promise after. What my CompnentWillMount code looks like is what I want to achieve.
  • your fetchStorage function doesn't return a promise it returns a function which will return a promise when invoked.So you can not chain a then to it.
  • Ah, thought maybe it had it's own returning for a promise and I did not need to wrap it.
  • @chobo2 certainly looks like it returns a promise. or, at least a thennable.