我正在尝试异步/等待功能.我有这样的代码模仿请求:
const getJSON = async () => {
const request = () => new Promise((resolve, reject) => (
setTimeout(() => resolve({ foo: 'bar'}), 2000)
));
const json = await request();
return json;
}
Run Code Online (Sandbox Code Playgroud)
当我以这种方式使用代码时
console.log(getJSON()); // returns Promise
Run Code Online (Sandbox Code Playgroud)
它返回一个Promise
但是当我调用这行代码时
getJSON().then(json => console.log(json)); // prints { foo: 'bar' }
Run Code Online (Sandbox Code Playgroud)
它按预期打印json
可以只使用像这样的代码console.log(getJSON())吗?我不明白什么?
因此,我在此上浪费了5个小时。
我有一个redux thunk动作,如下所示:
export const fetchUser = () => async (getState, dispatch) => {
if (getIsFetching(getState().user)) {
return Promise.resolve();
}
dispatch(fetchUserRequest());
try {
const response = await api.fetchUser();
dispatch(fetchUserSuccess({ userObject: { ...response } }));
} catch (error) {
dispatch(fetchUserFailure({ message: "Could not fetch user profile." }));
}
};
Run Code Online (Sandbox Code Playgroud)
调用它总是结束于“操作必须是普通对象。将自定义中间件用于异步操作。]”。
好,当然。我已经在使用redux-thunk了,为什么它一直困扰着我?
注意:fetchUserRequest(),fetchUserSuccess()和fetchUserFailure()都返回简单的普通redux操作。