用法: Promise.then(函式)
function printResult(a) {
console.log(a);
}
const request = fetch("https://run.mocky.io/v3/d2381372-4e30-4ec6-8a03-c3573417112d")
request.then(printResult)
關於 .then 的用法可參考:Promise.prototype.then()-MDN web Docs
const api500 = 'https://run.mocky.io/v3/74e65703-c9b2-4c4c-b36e-88d8cc6cd253'
const api200 = 'https://run.mocky.io/v3/d2381372-4e30-4ec6-8a03-c3573417112d'
const request = fetch(api200)
request.then(response => {
console.log(response.body)
}
)
會印出一個 ReadableStream Object。
const api500 = 'https://run.mocky.io/v3/74e65703-c9b2-4c4c-b36e-88d8cc6cd253'
const api200 = 'https://run.mocky.io/v3/d2381372-4e30-4ec6-8a03-c3573417112d'
const request = fetch(api200)
request.then(response => {
console.log(response.body)
}
)
如果用 .json() 的話,會直接回傳 JS 的物件型態。
fetch('url').then(res => {
res.text().then( text => {
return JSON.parse(text)
})
})
但是這樣印出的結果會是回傳一個 Promise 物件
const api500 = 'https://run.mocky.io/v3/74e65703-c9b2-4c4c-b36e-88d8cc6cd253'
const api200 = 'https://run.mocky.io/v3/d2381372-4e30-4ec6-8a03-c3573417112d'
const request = fetch(api200)
request.then(response => {
const result = response.text()
result.then(body => { console.log(body) })
}
)
流程:
fetch('url').then(res => console.log(res.body))
回傳會是一個 ReadableStream 實例。fetch('url').then(res => console.log(res.text()))
將會再回傳 Promise 物件,所以要用 .then 來解讀。fetch('url').then(res => {
res.text().then(result => {
console.log(result)
})
})
就可以拿到透過 fetch
回傳值複習:
fetch() => Promise Object
response.text() => Promise Object
response.body => ReadableStream Object
response.json().then() => Promise Object