首页 > 解决方案 > 我应该从这个异步函数返回什么?

问题描述

我是 javascript 中 Promises 的常规用户。现在,我想尝试异步/等待。但是由于对异步/等待的一半了解,我被困住了。

我有一个使用 Promise 的函数,如下所示:

const asyncRequest = (funcA, b) => {
  // do some syncronous stuff. e. g. console.log
  console.log(b);
  return funcA(b)
    .then((something) => console.log(something))
    .catch((err) => console.log(err))
}

我试图将上述基于 Promise 的代码转换为 async/await:

const asyncRequest = async (funcA, b) => {
  // do some syncronous stuff. e. g. console.log
  console.log(b);
  try {
    const something = await funcA(b);
    console.log(something);
  } catch (err) {
    console.log(err);
  }
}

函数转换看起来很简单。但我注意到我return的基于 Promise 的代码中有关键字。但是在我的异步/等待代码中,我很困惑。我应该返回什么?

真实例子:

基于承诺的例子

const Toast = {};

const createAsyncAction = ({
  asyncRequest, types, loadingPayload = null, showToastOnError = true,
}) => (dispatch) => {
  dispatch({
    type: types.loading,
    payload: loadingPayload,
  });

  return asyncRequest()
    .then((response) => {
      if (response.isMock) { // if mock request
        dispatch({
          type: types.success,
          payload: response.payload,
        });
        return;
      }

      if ([2, 3].includes(String(response.status).substring(0, 1))) { // if request succeeds
        response.json()
          .then((res) => {
            if (res.statusCode === 1000) {
              dispatch({
                type: types.success,
                payload: res.data,
              });
              return;
            }
            dispatch({ // if its a known error by server
              type: types.failure,
              payload: {
                code: res.statusCode,
                message: res.message,
              },
            });
            if (showToastOnError) {
              Toast.error(`${res.statusCode}: ${res.message}`);
            }
          }).catch((error) => { // if response is not convertible to json
            dispatch({
              type: types.failure,
              payload: {
                code: response.status,
                message: error.message,
              },
            });
            if (showToastOnError) {
              Toast.error(`${response.status}: ${error.message}`);
            }
          });
        return;
      }

      dispatch((error) => { // if request fails with some status codes like 404, 500...
        dispatch({
          type: types.failure,
          payload: {
            code: response.status,
            message: error.message,
          },
        });
        if (showToastOnError) {
          Toast.error(`${response.status}: ${error.message}`);
        }
      });
    }).catch(() => { // if request cannot be made due to some internet or connection issue
      dispatch({
        type: types.failure,
        payload: {
          code: 0,
          message: 'Connection issue. Make sure your are connected to the internet and that your API is working',
        },
      });
      if (showToastOnError) {
        Toast.error('Connection issue. Make sure your are connected to the internet and that your API is working');
      }
    });
};

export default createAsyncAction;

异步/等待示例:

const Toast = {};

const createAsyncAction = ({
  asyncRequest, types, loadingPayload = null, showToastOnError = true,
}) => async (dispatch) => {
  dispatch({
    type: types.loading,
    payload: loadingPayload,
  });

  try {
    const response = await asyncRequest();
    if (response.isMock) { // if mock request
      dispatch({
        type: types.success,
        payload: response.payload,
      });
      return;
    }

    if ([2, 3].includes(String(response.status).substring(0, 1))) { // if request succeeds
      try {
        const jsonResponse = await response.json();
        if (jsonResponse.statusCode === 1000) {
          dispatch({
            type: types.success,
            payload: jsonResponse.data,
          });
          return;
        }
        dispatch({ // if its a known error by server
          type: types.failure,
          payload: {
            code: jsonResponse.statusCode,
            message: jsonResponse.message,
          },
        });
        if (showToastOnError) {
          Toast.error(`${jsonResponse.statusCode}: ${jsonResponse.message}`);
        }
      } catch (error) {
        dispatch({
          type: types.failure,
          payload: {
            code: response.status,
            message: error.message,
          },
        });
        if (showToastOnError) {
          Toast.error(`${response.status}: ${error.message}`);
        }
      }
      return;
    }

    dispatch((error) => { // if request fails with some status codes like 404, 500...
      dispatch({
        type: types.failure,
        payload: {
          code: response.status,
          message: error.message,
        },
      });
      if (showToastOnError) {
        Toast.error(`${response.status}: ${error.message}`);
      }
    });
  } catch (_) {
    dispatch({
      type: types.failure,
      payload: {
        code: 0,
        message: 'Connection issue. Make sure your are connected to the internet and that your API is working',
      },
    });
    if (showToastOnError) {
      Toast.error('Connection issue. Make sure your are connected to the internet and that your API is working');
    }
  }
};

export default createAsyncAction;

标签: javascriptasynchronousecmascript-6

解决方案


你不需要一个!

任何标记为的函数async将始终返回一个承诺。现在,如果您希望该承诺解决某些问题,那么您需要返回一个值。但是,由于您只是在做console.log,它的返回值为undefined,这相当于什么都不返回(因为undefined如果没有指定的返回值,JavaScript 将隐式返回)。

async文档

异步函数是通过事件循环异步操作的函数,使用隐式Promise返回其结果。

因此,async将隐式返回包装在 a 中的函数的任何返回值Promise


推荐阅读