vue fetch中的.then()的正確使用方法
先看一段代碼:
fetch(’http://localhost:3000/books?id=123456’,{ method:’get’}).then(function(value1){ console.log(value1); return ’hello’;}).then(function(value2){ console.log(value2); return ’HelloWorld’;})/*.then(function(data){ console.log(data); return data.text(); })*/.then(data=>{ console.log(data);})
// 接口app.get(’/books’, (req, res) => { res.send(’傳統(tǒng)的URL傳遞參數(shù)!’ + req.query.id)})
在這段代碼中我們發(fā)現(xiàn),最初傳入的是一個(gè)對(duì)象,緊接著后一個(gè).then()的傳入?yún)?shù)使用了前一個(gè).then()的返回值,換句話說(shuō),就是后一個(gè)then使用前一個(gè)then的封裝結(jié)果
那么現(xiàn)在去掉注釋:
.then(function(value2){ console.log(value2); return ’HelloWorld’;}).then(function(data){ console.log(data); return data.text(); })text()方法屬于fetch API的一部分,返回一個(gè)Promise實(shí)例對(duì)象,用于獲取后臺(tái)返回的數(shù)據(jù)
這段代碼中,傳入的data是上一步封裝的字符串,所以此時(shí)用data.text()報(bào)錯(cuò),除非data為對(duì)象
下面演示正確使用方式:
fetch(’http://localhost:3000/books?id=123456’,{ method:’get’}).then(function(data){ console.log(data); console.log(typeof(data)); return data.text();}).then(data=>{ console.log(data); console.log(typeof(data));})
輸出了接口詢問(wèn)的內(nèi)容,為String類型
到此這篇關(guān)于vue fetch中的.then()的正確使用方法的文章就介紹到這了,更多相關(guān)vue fetch .then()內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Java類加載機(jī)制實(shí)現(xiàn)步驟解析2. XML入門的常見(jiàn)問(wèn)題(二)3. jsp文件下載功能實(shí)現(xiàn)代碼4. JSP之表單提交get和post的區(qū)別詳解及實(shí)例5. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法6. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案7. XML入門的常見(jiàn)問(wèn)題(一)8. ASP常用日期格式化函數(shù) FormatDate()9. ASP.NET MVC使用異步Action的方法10. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享
