代码之家  ›  专栏  ›  技术社区  ›  Vishal

我应该从这个异步函数返回什么?

  •  0
  • Vishal  · 技术社区  · 6 年前

    我有一个使用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))
    }
    

    我已尝试将上述基于承诺的代码转换为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

    实例:

    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;
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Matthew Herbst    6 年前

    你不需要!

    任何标记为 async 会永远回报你的承诺。现在,如果你希望这个承诺能解决一些问题,那么你需要返回一个值。不过,既然你只是 console.log ,其返回值为 undefined 未定义 如果没有指定的返回值)。

    async docs :

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

    所以, 异步 将隐式返回包装在 承诺

        2
  •  0
  •   Ruzihm aks786    6 年前

    你不需要退货。这不是导致代码差异的原因。在您的示例中,您需要使用 await 当您调用funcA(b)时,因为您想让js在解析时做其他事情。

    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);
      }
    }
    
        3
  •  -1
  •   lonesomeday    6 年前

    这两个函数都返回承诺。

    async 根据定义,函数返回承诺。因此,“returna Promise”消息隐含在第二个函数中。

    当您从 异步 函数,也就是用它来解决承诺的值。如果你不归还任何东西,承诺将与价值一起解决 undefined .then((something) => console.log(something)) . 当然,这是, 未定义