[英]Javascript - Response undefined fetch
我在使用fetch理解變量和函數時遇到了一些問題。 我正在嘗試傳遞來自的響應值
.then(response => response.json())
至
.then(lang => response['lang'].slice(-2)
但是我收到未定義的變量響應錯誤,所以我沒有正確引用變量。 正確的調用方式是什么?
我也想同時調用兩個控制台日志,下面的代碼段目前可以做到這一點,但是我不認為我應該覆蓋響應函數,我可以自己調用沒有參數或命令的函數嗎?
.then(response => console.log(response['text']) & console.log(food))
console.log(response ['text'])和console.log(food)
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(lang => response['lang'].slice(-2))
.then(food => "Temporary")
.then(function detectType(lang) {
switch(lang) {
case 'abc':
food = "Bananas";
break;
case 'def':
food = "Apples";
break;
default:
food = "Bananas";
break;
}})
.then(response => console.log(response['text']) & console.log(food))
.catch(err => console.error(err));
}
如果我了解要執行的操作,請記住一個函數的返回值就是下一個函數接收到的狀態。 因此,您將希望做更多這樣的事情:
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(response => {
response['lang'] = response['lang'].slice(-2);
return response;
})
.then(response => {
response['food'] = "Temporary";
return response;
})
.then(function detectType(response) {
switch(response['lang']) {
case 'abc':
response['food'] = "Bananas";
break;
case 'def':
response['food'] = "Apples";
break;
default:
response['food'] = "Bananas";
break;
}
return response;
})
.then(response => {
console.log(response['text']);
console.log(response['food']);
})
.catch(err => console.error(err));
}
關於fetch()
,請記住它非常“承諾繁重”。
fetch("https://localhost:8000", {method:"POST", body:fd})
返回一個Promise,您可以使用第一個then()
then(response => response.json())
返回response.json()
會在下一個.then()
為您提供response.json()
的狀態。 因此,您可以通過下一個then()
訪問響應的JSON表示形式。
讓我們看一下它的外觀:
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(jsonResp => jsonResp['lang'] );
在最后一行,您可以檢查JSON對象及其鍵,而無需遵循Promise鏈。 如果要檢查lang
屬性,則可以按在示例中看到的方式對其進行訪問。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.