javascript - 如何返回一个简单的 redux Action 创建者的 promise ?

标签 javascript ecmascript-6 redux

我有一个函数 add,其中没有 promise 返回给调用者。

例如:

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

在我的应用程序的另一个功能中,我想做的是:

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

我只想等到 add() 完成,然后再做其他事情。我了解 async save 不返回 promise 。它是一个简单的 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 } });
});
};

我把它贴在这里是为了显示 Action

最佳答案

在我看来,您正在使用 redux-thunk 进行异步操作,因为您的 add 操作创建者实际上返回了一个接受 dispatch 的函数,而不是一个简单的 Action 对象。

如果您使用的是 redux-thunk,那么无论您从 thunk 返回什么,都将被传回。因此,如果您修改代码:

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

然后将你的 thunk 更新为:

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

(您会注意到我删除了最外面的 curl ),然后 ApiUtil 的 promise 应该会一直冒泡回来,您应该能够 .then 在它上面。

关于javascript - 如何返回一个简单的 redux Action 创建者的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48196734/

相关文章:

javascript - 支持旧浏览器与 terser + rollup 吗?

javascript - Redux 商店帮助 : Students and Schools

redux-auth-wrapper 重定向不起作用

javascript - 将所有单选按钮设置为 false,然后在 Redux reducer 中将其中一个设置为 true

javascript - 错误 [ERR_PACKAGE_PATH_NOT_EXPORTED] : No "exports" main defined in package. json

Grails 中的 Javascript 表格单击功能

javascript - 将 'this' 传递给类 ecmascript 6 中的回调

javascript - JS如何实现随机多张图片不重复显示?

javascript - 按 Angular 4 中的多列分组

javascript - JSX 生成 div 并推送到数组