当我使用 redux-thunk 时,promise 与 async 之间有什么不同?

what is different between promise vs async when I use redux-thunk?

嗨,我对 redux thunk 的工作原理有点困惑。 例如,

此代码有效

代码 1

export const getAllUsers = () => (dispatch) => {
  axios
    .get("https://reqres.in/api/users?page=2")
    .then((res) => {
      console.log(res);
      dispatch({ type: GET_ALL_USER, payload: res.data.data });
    })
    .catch((e) => console.log(e));
};

但此代码无效...

code2

export const fetchComments = () => () => {
  axios
    .get("https://jsonplaceholder.typicode.com/posts/1/comments")
    .then((res) => {
      return {
        type: FETCH_COMMENTS,
        payload: res.data,
      };
    });
};

但是这段代码是有效的..

code3

 export const fetchComments = async() => {
     let res = await axios.get("https://jsonplaceholder.typicode.com/posts/1/comments")
     return {
         type: FETCH_COMMENTS,
         payload:res.data
       }
   ;
 };

所以我真的很想知道为什么 code2 不工作,为什么 code3 工作。

为什么代码 #1 有效? - 调度

此函数调用调度,让 redux-thunk 了解下一步要做什么

export const getAllUsers = () => (dispatch) => {
  axios
    .get("https://reqres.in/api/users?page=2")
    .then((res) => {
      console.log(res);
      dispatch({ type: GET_ALL_USER, payload: res.data.data }); // Calling a dispatch, which is a clear trigger for the middleware
    })
    .catch((e) => console.log(e));
};

为什么代码 #2 不起作用 - 更高范围不是异步的

你不能在这里调用 await fetchComments,因为你从未将 fetchComments 定义为异步,所以 redux-thunk 没有得到你期望的

export const fetchComments = () => () => { // This is a plain function, noy an asynchronous one, meaning that the middlware won't get the result it is expecting
  axios
    .get("https://jsonplaceholder.typicode.com/posts/1/comments")
    .then((res) => {
      return {
        type: FETCH_COMMENTS,
        payload: res.data,
      };
    });
};

为什么代码 #3 有效 - 更高的范围是异步的

这可以称为await fetchComments,因为你已经在async () => ...中定义了它,因此,redux-thunk理解它

 export const fetchComments = async() => { // Clearly defined to be async
     let res = await axios.get("https://jsonplaceholder.typicode.com/posts/1/comments")
     return {
         type: FETCH_COMMENTS,
         payload:res.data
       }
   ;
 };

所以回答你的问题,当你使用 redux-thunk 时,promise 和 async 有什么区别?

getAllUsers() => 这将在 Promise 完成后触发 dispatch({...}),这就是它起作用的原因 - 与 Promise 和 Async

没有什么特别的关系

fetchComments() => 这将 return 一个普通函数 returning 一个对象,在 Promise 完成后,这对 redux-thunk

async fetchComments() => 这可以通过 await 正确处理以获取完成的结果(对象),就像在上面的函数中一样,但它可以被处理,因为它是异步的。

所以,问题不在于 Promise 与 Async,而是你如何调用函数和定义它们,你可以使用 Promise 或 Async