Fetch call freezes

雨燕双飞 提交于 2019-12-11 14:10:25

问题


I am using fetch to read data from a API:

async _getDcnDetail(dcnId) {

         return await fetch(API_URL+'get_dcndetail', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization':'Bearer '+ this.state.accessToken
            },                
            body: JSON.stringify({
                DcnId: dcnId
            })
        }).then(response => response.json());

    }

Then I call it:

async componentDidMount() {

   let response = await this._getDcnDetail(dcn.DcnId);
   console.log(response);

}

But it "waits" eternally, it is not resolving the promise.

As I understand fetch returns a promise which gets resolved by response.json(). I use "await" to wait the promise to be resolved, so not sure, what is wrong.


回答1:


First of all check if some error occured on your POST request

async _getDcnDetail(dcnId) {

         return await fetch(API_URL+'get_dcndetail', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization':'Bearer '+ this.state.accessToken
            },                
            body: JSON.stringify({
                DcnId: dcnId
            })
        }).then(response => response.json())
          .catch(err => alert("maybe some error occured"));
    }

Additionally, you should refactor this as,

async _getDcnDetail(dcnId) {

         try{
          const response = await fetch(API_URL+'get_dcndetail', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization':'Bearer '+ this.state.accessToken
            },                
            body: JSON.stringify({
                DcnId: dcnId
            })
          });
          response = response.json();
          return response;
         } catch(e){
           console.log("error", e);
           throw err;
         }
    }

Do have a look on promises and async/await



来源:https://stackoverflow.com/questions/57661630/fetch-call-freezes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!