javascript - 如何在 JS 中将以前的数据与 .catch 一起使用?
问题描述
await populartimes(markers[i].placeID)
.then(out => {temp = 'Currently ' + out.now.currently + ' full.'})
.catch(out => {temp = 'Live data is not currently available. Historically, ' + markers[i].name + ' would be ' + out.now.usually + ' full.'})
.catch(out => {temp = 'There is currently no data available.'});
我正在尝试使我的第一个 .catch 语句再次使用第一个返回的数据,除了这次检查另一个变量(now.通常而不是 now.currently 在 .then 语句中检查)。我该怎么做呢?我已经写了这个,但我很确定传递给第一个 .catch 的输出只是来自 .then 的错误语句。
蒂亚!
解决方案
不幸的是,在抛出错误后,promise 不会对数据值进行curry。您已经在使用一个临时变量,为什么不使用两个呢?:
var temp;
var out!: any;
await populartimes(markers[i].placeID)
.then(value => {
out = value;
temp = 'Currently ' + out.now.currently + ' full.';
})
.catch(() => {
temp = 'Live data is not currently available. Historically, ' + markers[i].name + ' would be ' + out.now.usually + ' full.';
})
.catch(() => {
temp = 'There is currently no data available.';
});
但是,对于将 promise 处理与 await 语句混合使用,我会持谨慎态度。如果populartimes
是异步函数,您的代码将按预期工作,但是如果它是返回承诺的普通函数,则您的代码将不会处理抛出错误的情况(返回承诺的函数可以拒绝承诺或抛出错误)。
仅使用await
,try/catch
您的代码将相当于:
var temp;
try {
var out = await populartimes(markers[i].placeID);
try {
temp = 'Currently ' + out.now.currently + ' full.';
} catch {
temp = 'Live data is not currently available. Historically, ' + markers[i].name + ' would be ' + out.now.usually + ' full.';
}
} catch {
temp = 'There is currently no data available.';
}
推荐阅读
- mysql - SQL 命令错误/外键问题
- python - 使用字典中给出的单词出现更新数据框的单元格
- javascript - 如何使用 HTML 和 Javascript 在没有按钮的情况下更改背景图像
- extension-methods - OnAfterOpenSolution 和 OnAfterOpenProject 未触发,将扩展升级到 Visual Studio 2022
- python - 满足 PyDispatcher-2.0.5 的要求(来自版本:无)
- powershell - 简单的powershell成功或失败日志
- regex - 为什么 '['||chr(128)||'-'||chr(255)||']' 不起作用
- javascript - 将 Scrapy spider 作为脚本运行不会获得所有代码,但来自项目的 scrapy spider 会
- python - 如何在循环上制作数字生成器,并将每次重复限制为最多100个,以便生成的数字数量为100个数字
- javascript - 使用 javascript 突出显示 CSS 网格布局中的元素