react.js - 请问 使用 redux-promise-middleware 应该怎么设置 payload 为 async 函数 呢?
本文介绍了react.js - 请问 使用 redux-promise-middleware 应该怎么设置 payload 为 async 函数 呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
例如
export function asyncAdd ( data ) {
return ({
type: 'ADD',
payload: (async () => {
fetch('http://add.com').then(( response ) => {
return response;
})
})()
// payload: new Promise(resolve => {
// fetch('http://add.com').then(response => {
// resolve();
// });
// })
})
}
发现直接 使用 async 返回的 Promise 会导致立即执行了 ADD_FULFILLED。
而使用 new Promise 是正常的异步返回。
请问 如果需要使用 async 函数应该如何 注册 payload ?
解决方案
async/await
这两个是配对使用的,如果没有 await 是不会等待的
async () => {
await fetch('http://add.com');
}
PS:
fetch
本身就返回 Promise,不需要再包装一层
参考:
这篇关于react.js - 请问 使用 redux-promise-middleware 应该怎么设置 payload 为 async 函数 呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文