您的位置:首頁/技術文章
文章詳情頁

java - fetchAPI代替ajax請求為什么不走第二個then而直接走了catch?

【字号: 作者:豬豬瀏覽:97日期:2023-12-21 09:59:04

問題描述

var serverUrl = 'http://43.254.150.58/b2c-web-cib'; //接口服務器fetch(serverUrl + ’/api/home/mallHome’, { method: ’post’, headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: ’json={}’}).then(function(response){ console.log(response.json()); return response.json();}).then(function(data){ console.log(data);}).catch(function(e) { console.log('出錯了');});

console出來的結果是這樣的Promise {[[PromiseStatus]]: 'pending', [[PromiseValue]]: undefined}出錯了我能肯定這個請求是成功的,而且展開這個Promise后是有值得,返回的值也正確,那到底哪里出了問題呢?為什么不走第二個then,而直接走了catch呢?我打印 一下這個catch里的參數e,結果是TypeError: Already read at test.html:19,意思是我在第一次then的時候已經讀取過了

對了,如果我想用async/await代替Promise應該怎么寫呢?

問題解答

回答1:

問題出在你第一個then的console.log上

response是只能被讀取一次的,當調用了bolb,json,text或者其他幾個讀取的接口之后,esponse的bodyUsed被設為true,就不能在此讀取了

console.log(response.json()); //第一次讀取return response.json(); //又讀取了一次

讀取了兩次,自然就報錯已經讀取的錯誤了所以你把第一個then改成這樣就可以了

let jsonPromise = response.json() console.log(jsonPromise); return jsonPromise;

改成async/await的話,大概是這樣,不保證正確..

let doFetch = async () => { try {let resp = await fetch(serverUrl + ’/api/home/mallHome’, { method: ’post’, headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: ’json={}’})let json = await resp.json() } catch (e) {console.log('出錯了') }}

標簽: java
相關文章:
国产综合久久一区二区三区