将承诺转换为异步/等待 - Javascript [英] Converting promises to async/await - Javascript

查看:27
本文介绍了将承诺转换为异步/等待 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中有一个 dataService 函数来执行我的 API 获取.我尝试转换为 async/await 块,但似乎遇到了障碍.

I have a dataService function in React that does my API fetching. I tried converting to async/await block but seem to hit a roadblock.

使用承诺:

const dataService = (url, options, dataToPost) => {

    return (dispatch, getState) => {
        const { requestAction, successAction, failureAction } = options.actions;

        if (options.shouldRequest(getState())) {
            dispatch(requestAction());
            const promise = axios.get(url, { withCredentials: true });
            return promise
                .then(response => {
                    if (response.status === 200) {
                        return dispatch(successAction(response, dispatch));
                    }
                    return Promise.reject(response);
                })
                .catch(error => {
                    if (error.response.status === 302) {
                        window.location = '/view';
                    }
                    dispatch(openErrorDialog());
                    return dispatch(failureAction(error));
                });
        }
        return Promise.reject(new Error('FETCHING'));
    };
};

使用异步/等待:

	const dataService = async (url, options, dataToPost) => {

	    return async (dispatch, getState) => {
	        let url;
	        const {requestAction, successAction, failureAction} = options.actions;

	        if (options.shouldRequest(getState())) {
	            dispatch(requestAction());
	            const promise = axios.get(url, {withCredentials: true});
	            try {
	                const response = await promise;
	                if (response.status === 200) {
	                    return dispatch(successAction(response, dispatch));
	                }
	                return Promise.reject(response);
	            } catch (error) {
	                return dispatch(failureAction(error));
	            }
	        }
	        return Promise.reject(new Error('FETCHING'));
	    };
	};

错误是操作必须是普通对象.对异步操作使用自定义中间件.".承诺代码完美运行.我已经在使用 thunk.请指教.

The error is "Actions must be plain objects. Use custom middleware for async actions.". The promises code works perfecty. I am already using thunk. Please advice.

推荐答案

如果你真的想改变 Promise -> async/await 那么改变如下:

If you truly want to change Promise -> async/await then the changes are as follows:

首先,你不希望 dataService 是 async,因为这意味着它返回一个 Promise,它改变了它需要的调用方式——你不知道

For a start, you DONT want dataService to be async as that will mean it returns a Promise, which changes how it needs to be called - you dont' wnat that

其次,改变

  const promise = axios.get ...
  promise.then(response ....

  const promise = await axios.get ...
  promise.then(response ....

行不通...

必须的

const response = await axios.get ...

不需要承诺变量

即便如此,您在转换后的代码中仍在使用 promises ......现在只是无缘无故使用 async 关键字而有所不同

Even so, you're still using promises in your converted code ... which now is only different by having async keywords for no reason

这是您的(原始)代码应如何转换为 async/await

Here's how your (original) code should be converted to async/await

请注意以下 Promise 一词的缺失:

note the total LACK of the word Promise in what follows:

const dataService = (url, options, dataToPost) => {

    return async (dispatch, getState) => {
        const { requestAction, successAction, failureAction } = options.actions;

        if (options.shouldRequest(getState())) {
            const data = typeof dataToPost === 'string' ? { data: dataToPost } : dataToPost;
            dispatch(requestAction());
            try {
                const response = dataToPost
                    ? await axios.post(url, data, { withCredentials: true })
                    : await axios.get(url, { withCredentials: true });
                if (response.status === 200) {
                    return dispatch(successAction(response, dispatch));
                }
                throw response;
            } catch(error) {
                if (error.response.status === 302) {
                    window.location = '/view';
                }
                dispatch(openErrorDialog());
                return dispatch(failureAction(error));
            }
        }
        throw new Error('FETCHING');
    };
};

这篇关于将承诺转换为异步/等待 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆