admin管理员组

文章数量:1297044

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

  ponentWillMount() {
        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);
                });
        });
    };
}

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

  ponentWillMount() {
        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);
                });
        });
    };
}
Share Improve this question edited Aug 19, 2016 at 20:20 chobo2 asked Aug 19, 2016 at 18:44 chobo2chobo2 85.9k207 gold badges551 silver badges861 bronze badges 6
  • 2 Why not return instance.get('/Storage/Get') am I missing something here? – Daniel Kobe Commented Aug 19, 2016 at 18:49
  • 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 Commented Aug 19, 2016 at 19:50
  • 1 @chobo2 i don't understand why you aren't returning the promise that axios is already giving you. – Kevin B Commented Aug 19, 2016 at 20:35
  • 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. – chobo2 Commented Aug 19, 2016 at 20:58
  • 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. – Redu Commented Aug 20, 2016 at 10:29
 |  Show 1 more ment

3 Answers 3

Reset to default 2

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);
                });
    };
}

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()
});

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);
        });

 });

本文标签: javascriptReturn Promise from AxiosStack Overflow