我是新來使用async/await
- 我試圖從API調用返回數據並格式化/稍微清理它。如何正確實現異步/等待
由於函數的異步性質,我真的很努力地研究如何使這項工作。如果沒有瀏覽器的簡單翻版,我無法承諾工作。
我的第一個函數調用API並獲取響應爲JSON。然後我保存這個數據json.recommendations
function getRecs() {
const requestUrl = `blahblah`;
const options = {
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
},
method: 'GET',
};
fetch(requestUrl, options).then((res) => {
if (res.ok) {
return res.json();
}
throw new Error('Error!!??', res);
}).then((json) => {
return json.recommendations;
});
}
我的第二個函數接受json.recommendations
和做一些整理,以刪除不需要的數據並返回數據,那些符合我的過濾器的新陣列的一個子集。
async function getInStockRecs() {
const recs = await getRecs();
if (recs !== undefined) {
return recs.filter(function(rec){
return rec.isInStock === true;
});
}
}
的第三個功能進一步格式化數據:
async function topThreeArray() {
const inStockRecs = await getInStockRecs();
const topThree =[];
for (let i = 0; i < i <= 3; i++) {
topThree.push(inStockRecs[0]);
}
return topThree;
}
通過使用await
我打算每個功能僅一旦數據已經從以前的正常運行返回。然而,運行上述崩潰的頁面,我不能做任何事情來調試,因爲它只是崩潰。我哪裏錯了?