首页 > 解决方案 > 如何在 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 的错误语句。

蒂亚!

标签: javascript

解决方案


不幸的是,在抛出错误后,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是异步函数,您的代码将按预期工作,但是如果它是返回承诺的普通函数,则您的代码将不会处理抛出错误的情况(返回承诺的函数可以拒绝承诺或抛出错误)。

仅使用awaittry/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.';
}

推荐阅读