JavaScript异步函数祸害

问题描述 投票:0回答:1

假设我有一个Web应用程序在/exchange_rate/ccy1/ccy2返回给定货币对的汇率,每当在数据库中找不到货币对时,Web应用程序返回404。

在前端JavaScript代码中,为了防止故障,每当本地汇率查询失败时,我都会查询公共提供商,比如currencyconverterapi.com

让我们假设由于某种原因(实际代码使用Vue生命周期钩子),全局变量rate,并且这两个函数不能合并,也不能变成异步。

以下代码的问题是它只适用于本地查询axios.get('/exchange_rate/EUR/' + ccy)解析;当它拒绝时,amount * rate将在axios.get('http://free.currencyconverterapi.com...)设置rate之前执行 -

var rate;

function getExchangeRate(ccy) {
    return axios.get('/exchange_rate/EUR/' + ccy)
    .then(ret => {
        rate = ret.data.rate;
    }).catch(err => {
        axios.get('http://free.currencyconverterapi.com/api/v5/convert?q=EUR_' 
        + ccy).then(ret => {
            rate = ret.data.results.val;
        });
    });
}

function toEUR(ccy, amount) {
    getExchangeRate(ccy)
    .then(() => {
        return amount * rate;
    });
}

var EURAmount = toEUR('USD', 42);

我的问题是:有没有办法保证rategetExchangeRate中正确设置toEUR

javascript asynchronous promise
1个回答
3
投票

then函数中的toEUR不等待第二个请求完成,因为你不是return中的catching。

您也不应该为rate变量使用共享状态。只需将其作为您承诺的结果归还。

function getExchangeRate(ccy) {
    return axios.get('/exchange_rate/EUR/' + ccy)
    .then(ret => ret.data.rate)
    .catch(err => {
        return axios.get('http://free.currencyconverterapi.com/api/v5/convert?q=EUR_' 
        + ccy)
            .then(ret => ret.data.results.val);
    });
}

function toEUR(ccy, amount) {
    return getExchangeRate(ccy)
        .then(rate => amount * rate);
}

toEUR('USD', 42)
    .then(amount => console.log(amount))
    .catch(err => console.error(err));

我建议将备份调用分解为一个单独的函数,这样你就没有嵌套的promise:

function getExchangeRatePublicProvider(ccy) {
    return axios.get('http://free.currencyconverterapi.com/api/v5/convert?q=EUR_' 
        + ccy)
        .then(ret => ret.data.results.val);
}

function getExchangeRate(ccy) {
    return axios.get('/exchange_rate/EUR/' + ccy)
        .then(ret => ret.data.rate)
        .catch(err => getExhangeRatePublicProvider(ccy));
}

function toEUR(ccy, amount) {
    return getExchangeRate(ccy)
        .then(rate => amount * rate);
}

toEUR('USD', 42)
    .then(amount => console.log(amount))
    .catch(err => console.error(err));
© www.soinside.com 2019 - 2024. All rights reserved.