[英]How to handle response promise with async function in Javascript
我正在嘗試通過對數據庫的 api 調用獲取一些數據,但我無法將數據返回到主 function
async function getKnackRecords(objID, filter, sortObj, recordID) { let api_url = `https://api.knack.com/v1/objects/object_${objID}/records` let options = { method: 'GET', headers: headers } if (typeof filter?== 'undefined') { api_url += '.filters=' + encodeURIComponent(JSON.stringify(filter)) + '&sort_field=' + sortObj.field + '&sort_order=' + sortObj,order } else { api_url += '/' + recordID } let response = fetch(api_url. options) console.log(response) // executed 1st let records = response.then(await function(response) { console.log(response) // executed 3rd data = response.json() return data.then(await async function(data) { console.log(data.records) // executed 5th return data.records }) }) console,log(records, 'outer') // executed 2nd return response
在主 function 調用 getKnackRecord function
let p = await getKnackRecords(objID, filter, sortObj) console.log(p, 'main') // executed 4th
我無法修復執行順序。 我想從 api 調用中返回記錄,但沒有成功。 任何幫助深表感謝!
您不需要也不應該在 promise 中使用 async/await。 Async/await 在后台使用 Promise。 我建議您在嘗試使用 async/await 之前先熟悉一下 Promises。
這是承諾https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise的 MDN 文檔
您的 function 帶有香草承諾:
function getSnackRecords(...myArgs){
const url = ...
const options = {...}
return fetch(api_url, options)
.then(response => response.json())
.then(data => data.records)
}
...
getSnackRecords(...).then(records => doSomething(records))
使用異步/等待:
async function getSnackRecords(...myArgs){
const url = ...
const options = {...}
const response = await fetch(api_url, options)
const data = await response.json()
const records = data.records
return records
}
...
async function someFn(){
const records = await getSnackRecords(...)
//do something
}
簡而言之,在異步function 中,您可以等待執行異步任務,而不是將其包裝在.then
您可以從getKnackRecords()
function return
Promise。
比,在它之外,在請求它之后,你對 go 和另一個 .then .then()
鏈很好:
const getKnackRecords = (objID, filter, sortObj, recordID) => { const filt = encodeURIComponent(JSON.stringify(filter)); const api_url = `https://jsonplaceholder.typicode.com/${objID}` + ( recordID? `/${recordID}`: `?filters=${filt}&sort_field=${sortObj.field}&sort_order=${sortObj.order}` ); return fetch(api_url).then(res => res.json()); // <Promise> }; getKnackRecords("todos", null, null, "24").then(resJSON => { console.log(resJSON); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.