【问题标题】:Fetch call freezes获取呼叫冻结
【发布时间】:2019-12-30 20:45:21
【问题描述】:

我正在使用 fetch 从 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());

    }

那我叫它:

async componentDidMount() {

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

}

但它永远“等待”,它并没有解决承诺。

据我了解,fetch 返回一个由 response.json() 解决的承诺。我用“await”来等待promise被解决,所以不确定,出了什么问题。

【问题讨论】:

  • 您是否检查了开发者工具以了解实际的 HTTP 请求是如何进行的?
  • 这段代码运行良好。检查api是否有问题或api url是否正确?
  • 如果您想在相关问题上帮助我:stackoverflow.com/questions/57662891/…
  • 提示:你不需要异步等待,因为你只是返回结果。

标签: javascript async-await fetch es6-promise


【解决方案1】:

首先检查您的 POST 请求是否发生错误

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"));
    }

此外,您应该将其重构为,

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;
         }
    }

看看promisesasync/await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2020-07-21
    • 1970-01-01
    • 2019-07-14
    • 2012-06-30
    • 1970-01-01
    相关资源
    最近更新 更多