1. 程式人生 > 程式設計 >vue fetch中的.then()的正確使用方法

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('傳統的URL傳遞引數!' + req.query.id)
})

vue fetch中的.then()的正確使用方法

在這段程式碼中我們發現,最初傳入的是一個物件,緊接著後一個.then()的傳入引數使用了前一個.then()的返回值,換句話說,就是後一個then使用前一個then的封裝結果

那麼現在去掉註釋:

vue fetch中的.then()的正確使用方法

.then(function(value2){
  console.log(value2);
  return 'HelloWorld';
})
.then(function(data){
   console.log(data);
   return data.text();
 })
text()方法屬於fetchAPI的一部分,返回一個Promise例項物件,用於獲取後臺返回的資料

這段程式碼中,傳入的data是上一步封裝的字串,所以此時用data.text()報錯,除非data為物件

下面演示正確使用方式:

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

vue fetch中的.then()的正確使用方法

輸出了介面詢問的內容,為String型別

到此這篇關於vue fetch中的.then()的正確使用方法的文章就介紹到這了,更多相關vue fetch .then()內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!