两种异步方法在类上结合

发布于 2025-02-08 17:49:38 字数 1111 浏览 0 评论 0原文

我在currency.js文件上有货币类,并且我

crurner.js中都有main.js文件,我想使用getExchangerate() 带有2个参数的功能,<代码>货币2 ),然后我想将此功能绑定到convert(nose)方法。我不想给出Currency1Currency2参数以再次转换方法。然后,我想在main.js中使用convert方法,例如convert(Currency1,Currency2,金额),但它不起作用。

class Currency{
    constructor(){
        
    }

    async getExchangeRate(currency1 , currency2){
        this.currency1=currency1;
        this.currency2 = currency2
        this.url = `https://api.exchangerate.host/convert?from=${currency1}&to=${currency2}`
        
        const excResponse = await fetch(this.url)
        const excResponseJSON = await excResponse.json()
        return excResponseJSON.result 
    }

   async convert(amount){
    this.amount = amount;
    let value1 = await this.getExchangeRate(currency1 , currency2)
    
    return value1 * amount;
   }
 
}

main.js

currency.convert("USD", "EUR", 3)
.then(response => console.log(response))
.catch(err => console.log(err))

I have Currency Class at currency.js file and i have main.js file

In currency.js I want to use getExchangeRate() function with 2 parameters (currency1, currency2) and then I want to bind this function to convert(amount) method. I dont want to give currency1 and currency2 params to convert method again. Then I want to use convert method in main.js like this convert(currency1, currency2, amount) but it doesnt work.

class Currency{
    constructor(){
        
    }

    async getExchangeRate(currency1 , currency2){
        this.currency1=currency1;
        this.currency2 = currency2
        this.url = `https://api.exchangerate.host/convert?from=${currency1}&to=${currency2}`
        
        const excResponse = await fetch(this.url)
        const excResponseJSON = await excResponse.json()
        return excResponseJSON.result 
    }

   async convert(amount){
    this.amount = amount;
    let value1 = await this.getExchangeRate(currency1 , currency2)
    
    return value1 * amount;
   }
 
}

main.js

currency.convert("USD", "EUR", 3)
.then(response => console.log(response))
.catch(err => console.log(err))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

述情 2025-02-15 17:49:38

正如@pilchard所说,咖喱方法可以“记住”参数bcz,它返回了示波器功能。也许是这样的?

async getExchangeRate(currency1, currency2) {
    
    // ...

    return function(amount) {
        return excResponseJSON.result * amount
    }
}

as @pilchard said, a curried method can "remember" the parameters bcz it returns a scoped function. Maybe something like this?

async getExchangeRate(currency1, currency2) {
    
    // ...

    return function(amount) {
        return excResponseJSON.result * amount
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文