reactjs .then()在异步函数调用中有什么用?它似乎什么都不做,从来没有被调用过?

b5lpy0ml  于 2022-11-22  发布在  React
关注(0)|答案(2)|浏览(204)

我有一个请求:

/*
    |--------------------------------------------------------------------------
    | Function : Get > User > Current Avatar
    |--------------------------------------------------------------------------
    */
    async function getUserCurrentAvatar() {

        // Ajax URL
        const ajax_url = process.env.NEXT_PUBLIC_FRONTEND_API_ROOT + 'user' + '/' + session.user.id + '/' + 'edit/avatar/getusercurrentavatar';

        /*
        |--------------------------------------------------------------------------
        | AJAX > Request
        |--------------------------------------------------------------------------
        */
        await axios.post(ajax_url)
            .then(response => {

                setCurrentUserAvatarId(response.data.id);
                setCurrentUserAvatarUrl(response.data.current_avatar);

            }).catch((error) => {

                // Error
                if (error.response) {
                    // The request was made and the server responded with a status code
                    // that falls out of the range of 2xx
                    // console.log(error.response.data);
                    // console.log(error.response.status);
                    // console.log(error.response.headers);

                } else if (error.request) {
                    // The request was made but no response was received
                    // `error.request` is an instance of XMLHttpRequest in the
                    // browser and an instance of
                    // http.ClientRequest in node.js
                    console.log(error.request);

                } else {
                    // Something happened in setting up the request that triggered an Error
                    console.log('Error', error.message);
                }
                console.log(error.config);

            });

    }

我用useEffect()的形式来命名它:

/*
    |--------------------------------------------------------------------------
    | Use Effect 1
    |--------------------------------------------------------------------------
    */
    useEffect(() => {

        // Session > Available
        if(session) {
            getUserCurrentAvatar();
        }

    }, [session]);

但我收到警告Promise returned from getUserCurrentAvatar is ignored, Add '.then()'
我的问题是我可以在.then()里面做副作用吗?
async function getUserCurrentAvatar() { ... }中,我将state设置为:

setCurrentUserAvatarId(response.data.id);
                setCurrentUserAvatarUrl(response.data.current_avatar);

我需要在设置currentUserAvatarUrl状态后执行sideEffect,我尝试在useEffect()中使用then(),但它不起作用:

/*
    |--------------------------------------------------------------------------
    | Use Effect 1
    |--------------------------------------------------------------------------
    */
    useEffect(() => {

        // Session > Available
        if(session) {
            getUserCurrentAvatar().then(() => {

                const fileName = 'myFile.jpg'
                imageSrcToFile(currentUserAvatarUrl, fileName).then();
                
            });
        }

    }, [session]);

then()中的匿名函数从未被触发,其中的任何功能都不起作用
但如果我像往常一样在另一个useEffect()中执行此操作,它将正常工作:

/*
    |--------------------------------------------------------------------------
    | Use Effect 2
    |--------------------------------------------------------------------------
    */
    useEffect(() => {

        const fileName = 'myFile.jpg'
        imageSrcToFile(currentUserAvatarUrl, fileName).then();

    }, [currentUserAvatarUrl]);

那么then()有什么用呢?为什么IDE每次都警告我在async函数调用之后包含then()

编辑:我尝试:

useEffect(() => {

        // Session > Available
        if(session) {
            getUserCurrentAvatar().then((response) => {

                alert(`Received response: ${JSON.stringify(response, null, 2)}`);

                const fileName = 'myFile.jpg'
                imageSrcToFile(currentUserAvatarUrl, fileName).then();

            });
        }

    }, [session]);

但我得到的是Received response: undefined

kgsdhlau

kgsdhlau1#

Async函数不直接返回值,它返回promise,因此需要then,您可以使用async-await,反之亦然。
代码的问题,因为getUserCurrentAvatar()没有返回任何东西,所以得到响应undefined。我已经更新了代码,如下所示。

function getUserCurrentAvatar() {
  // Ajax URL
  const ajax_url =
    process.env.NEXT_PUBLIC_FRONTEND_API_ROOT +
    "user" +
    "/" +
    session.user.id +
    "/" +
    "edit/avatar/getusercurrentavatar";

  /*
        |--------------------------------------------------------------------------
        | AJAX > Request
        |--------------------------------------------------------------------------
        */
  return axios
    .post(ajax_url)
    .then((response) => {
      //no need to set values on here first return, then set values on last promise
      // setCurrentUserAvatarId(response.data.id);
      // setCurrentUserAvatarUrl(response.data.current_avatar);
      return response.data;
    })
    .catch((error) => {
      if (error.response) {
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log("Error", error.message);
      }
      console.log(error.config);
    });
}

现在,您将能够获得响应,然后将该响应数据用于您的后续请求,如下所示。此外,如果您使用then,请避免使用asyncawait,反之亦然。

useEffect(() => {
  // Session > Available
  if (session) {
    getUserCurrentAvatar().then((response) => {
      alert(`Received response: ${JSON.stringify(response, null, 2)}`);

      const fileName = "myFile.jpg";
      imageSrcToFile(response.current_avatar, fileName).then();
    });
  }
}, [session]);
c7rzv4ha

c7rzv4ha2#

请尝试如下调整代码
1.在异步函数getUserCurrentAvatar内部-〉返回等待axios.post( AJAX _url),并且不要在那里添加处理程序。
1.在UseEffect内部调用异步函数并添加处理程序。

  1. setCurrentUserAvatarUrl(response.data.current_avatar,()=〉{ //在此处添加将在设置状态值后运行的代码});

相关问题