gpt4 book ai didi

javascript - 如何正确实现异步/等待

转载 作者:行者123 更新时间:2023-11-29 21:01:59 26 4
gpt4 key购买 nike

我刚开始使用 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 - 如何正确实现异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com