我被困在一個異步函式上,該函式通過執行來改變它的值。此函式呼叫“openlibrary”,它從函式引數中獲取 isbn 編號。所以呼叫庫成功,并fetch回傳一個圖書物件。我之前也列印了那個引數return,它仍然是正確的,直到回傳陳述句..
為什么該值在類建構式(intermediate value)的第二個引數處轉向?Book
class Book {
constructor(title, authors, isbn, id) {
this.title = title
this.authors = authors
this.isbn = isbn
this.id = id
}
}
const searchByISBN = async (isbn) => {
const url = `https://openlibrary.org/api/books?bibkeys=ISBN:\
${isbn}&jscmd=details&format=json`
const req = await fetch(url).catch(e => {
// Request failed
console.debug(e)
return null
})
const data = await req.json()
console.dir(data)
// No book with given isbn has been found
if (data[`ISBN:${isbn}`] === undefined)
return false
console.debug(isbn)
return new Book(data[`ISBN:${isbn}`].details.title,
data[`ISBN:${isbn}`].details.authors.map(a => a.name),
isbn, books.length)
}
...
// Inside some async function or browser console
book = await searchByISBN('1234567890')
...
控制臺輸出:
Object { "ISBN:1234567890": {…}
1234567890
Uncaught (in promise) TypeError: data[("ISBN:" (intermediate value))].details.authors is undefined
uj5u.com熱心網友回復:
“你好,共享同一個存在平面的人”——雷姆。我認為問題實際上可能出在您正在嘗試的 ISBN 上!
當我查看此鏈接提供的 JSON 時: https ://openlibrary.org/api/books?bibkeys=ISBN:1234567890&jscmd=details&format=json它沒有顯示任何作者。所以你的代碼很可能在被要求檢索作者后對為什么沒有作者感到困惑??
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477788.html
標籤:javascript 异步 返回
上一篇:解決承諾時擺脫未捕獲的錯誤
