Redux Saga async/await pattern

后端 未结 3 1157
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 13:14

I\'m using async/await throughout my codebase. Because of this my api calls are defined by async functions

async function apiFetchFoo {
  return await apiCall(..         


        
3条回答
  •  感动是毒
    2021-02-01 13:49

    As pointed out by Josep, await cannot be used inside a generator. Instead you need to use an async function. Also, note this is a limitation of async function itself. It is not imposed by redux-saga.

    Beyond this, I also wanted to mention that it is a conscious choice by the redux-saga authors to not allow devs to express sagas as async/await functions.

    Generators are more powerful than async/await and they allow advanced features of redux-saga like co-ordinating parallel tasks.

    Moreover, expressing sagas as generators help us define Effects which are plain objects defining the side effect. Effects makes it very easy to test our sagas.

    So, although your working code is fine, maybe not mixing up sagas and async function is a good idea.

    Just define your apiFetchFoo to return a promise which resolves with the response to the request. And when this happens your saga will resume with the results.

     const apiFetchFoo = () =>
       fetch('foo')
         .then(res => res.json())
    

提交回复
热议问题