简体   繁体   中英

How to return a promise for a simple redux action creator?

I have a function add where no promises is returned to the caller.

For example:

let add = (foo) => {this.props.save(foo)};

And in another function of my application I would like to do:

...
return  add()
        .then( ... do something else here ... );

I just want to wait till add() is done and then do something else. I understand async save does not return a promise. Its a simple redux action.

 export const save = (something) => (dispatch) => {

  ApiUtil.patch(`google.com`, { data: { 
 something  } }).
   then(() => {
  dispatch({ type: Constants.SET_FALSE });
  },
() => {
  dispatch({ type: Constants.SET_SAVE_FAILED,
    payload: { saveFailed: true } });
});
};

I have pasted it here to show action

It looks to me like you are using redux-thunk for async actions, since your add action creator is in fact returning a function that accepts dispatch rather than a simple action object.

If you are using redux-thunk, then whatever you return from your thunk will be propagated back out. So if you modify your code such that:

let add = (foo) => this.props.save(foo); // Now returns result of save

Then update your thunk to:

export const add = (something) => (dispatch) =>
    ApiUtil.patch(`google.com`, { data: { something } })
        .then(() => { dispatch({ type: Constants.SET_FALSE }); },
            () => { dispatch({ type: Constants.SET_SAVE_FAILED, payload: { saveFailed: true }});}
        );

(Where you'll notice I removed the outside-most curlies), then the promise from ApiUtil should bubble all the way back up and you should be able to .then on it.

First you have to understand what this.props.save() returns. If it returns a promise, then you need only return that from add:

const add = (foo) => { return this.props.save(foo); }

So the problem is just what the definition of save is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM