[英]JS How to extract data fro a promise
我正在努力從 API 調用中提取數據。 我需要它來返回一個鍵數組,但是當我嘗試渲染時,我不斷收到[object Promise]
。
const apiKey = '*****';
const container = document.getElementById('root');
const Yelp = {
async search(term, location, searchBy) {
let response = await fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${searchBy}`, {
headers: {
Authorization: `Bearer ${apiKey}`
}
})
if (response.ok) {
let jsonResponse = await response.json()
return jsonResponse.businesses.map(business => {
return business
})
}
}
}
console.log(Yelp.search('pasta', 'london', 'best_match'));
由於 Yelp.search function 是異步的,它總是會返回 promise。 這就是您在調用 promise 后記錄立即結果時觀察到它的原因。 相反,您應該等待 promise 像:
Yelp.search('pasta', 'london', 'best_match').then(results => {
console.log(results)
})
因此,要回答您的問題,您將調用 Promise 的 then() 方法等待其結果解決。 then 方法需要兩個 arguments。 第一個是您提供的用於處理 promise 的結果的 function。 第二個是您提供的 function,用於處理 promise 返回的任何錯誤。 例如:
Yelp.search('pasta', 'london', 'best_match').then(results => {
// handle the results
console.log(results)
}, err => {
// handle the error
console.error(err)
})
您還可以通過調用 catch() 來捕獲 promise 拋出的異常,如下所示:
Yelp.search('pasta', 'london', 'best_match')
.then(results => console.log(results), err => console.error(err))
.catch(ex => console.error(ex))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.