我刚开始使用 async/await
- 我正在尝试从 API 调用返回数据并稍微格式化/整理它。
由于函数的异步性质,我真的很难弄清楚如何使其工作。如果浏览器不崩溃,我就无法得到工作的 promise 。
我的第一个函数调用 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
,我希望每个函数仅在前一个函数正确返回数据后才运行。然而,运行上面的代码会导致页面崩溃,我无法执行任何调试操作,因为它只是崩溃了。我哪里出错了?
最佳答案
您没有在 getRecs()
中返回任何内容函数(您只需在 fetch()
调用的回调中返回)
由于您正在使用async-await
在其他地方,为什么不将其用于 getRecs()
也有功能吗?:
async function getRecs() {
const requestUrl = `blahblah`;
const options = {
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
},
method: 'GET',
};
const res = await fetch(requestUrl, options);
if (res.ok) {
return res.json().recommendations;
}
throw new Error('Error!!??', res);
}
否则,您必须返回 fetch()
调用自身:
return fetch(requestUrl, options).then((res) => {
...
浏览器崩溃的原因是for
中的条件循环输入topThreeArray()
很奇怪( i < i <= 3
)并导致无限循环。
基本上,i < i
计算结果为 false
,它被隐式强制为 0
,因此条件实际上变为 0 <= 3
这始终是正确的。
最后,我想指出,您应该仔细考虑是否 async-await
首先在浏览器中运行时是合适的,因为浏览器中对它的支持仍然非常脆弱和不稳定。
关于javascript - 如何正确实现 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053712/