gpt4 book ai didi

javascript - 异步/等待和 Redux Thunk : does calling 'dispatch' implicitly return a promise from the thunk?

转载 作者:行者123 更新时间:2023-11-30 11:08:17 25 4
gpt4 key购买 nike

我正在尝试围绕“async/await”思考,async 函数总是返回 Promises 并将异步函数与 Redux Thunks 结合使用这一事实 --

我知道 async 函数根据定义总是返回一个 promise 。但是,如果异步函数的最后一行不是 await 怎么办?

const foo = async (y, z) => {
await somethingElse()
const x = y + z;
}

foo 是否返回解析为 'x' 的 Promise 因为它在最后一行?如果不是,它返回什么 Promise

所以,在写一个thunk的时候,我有一个这样的函数

export const loadData = key => async (dispatch) => {
const url = 'http://something.com/api/v1/get_key';
const keyObj = { key };
const method = 'POST';
const headers = { 'Content-Type': 'application/json' };
const body = JSON.stringify(keyObj);

try {
const res = await isofetch(url, { method, headers, body });
const data = await res.json();
dispatch(loadDataSuccess(data));
} catch (e) {
debug('error with fetch', e.toString());
}

loadData 返回什么?我相信 dispatch 会返回一个Promise,那么 loadData 是否会隐式返回那个 Promise

如果最后一行是有什么区别吗

return dispatch(loadDataSuccess(data));

?感谢您的帮助!

最佳答案

const foo = async (y, z) => {
await somethingElse()
const x = y + z;
}

是的,这将返回 promise 。但它将是未定义的,因为您还没有解决它。

Promise {<resolved>: undefined}

等待完成后,foo 将获取已解析的数据。

I believe that dispatch returns a Promise

不,它没有。您需要从异步函数返回值,以便从 promise 中获取已解析的数据。因此,您将使用:

return dispatch(loadDataSuccess(data));

如果您不在异步函数中返回值,那么您将需要等待该 promise 以获取数据:

await foo(y, z) // without return
foo(y, z) // with return

所以从技术上讲,您的意见是如何处理您的异步 foo 操作。

关于javascript - 异步/等待和 Redux Thunk : does calling 'dispatch' implicitly return a promise from the thunk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54813456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com