【问题标题】:How can I store the value of a promise and use it once resolved?如何存储承诺的价值并在解决后使用它?
【发布时间】:2021-12-09 22:06:04
【问题描述】:

我目前正在开发一个与 uniswap 交互的应用程序,并且我已经开发了一个 Wrapper 类来包含我需要的关于某对(例如 DAI/WETH)的信息和变量。

由于其中一些值是异步的,我编写了一个 build() 异步函数来在调用构造函数之前获取这些值,以便我可以存储它们。我想将这个构建函数的结果(我定义的类的一个实例)存储在一个变量中以供以后使用,但我需要知道该构建函数返回的 Promise 在使用它之前是否已解决,所以我怎样才能做到?

这是类的代码:

'use strict'
const { ChainId, Fetcher, WETH, Route, Trade, TokenAmoun, TradeType, TokenAmount } = require('@uniswap/sdk')
const { toChecksumAddress } = require('ethereum-checksum-address')
const Web3 = require('web3')
const web3 = new Web3()
const chainId = ChainId.MAINNET;
let tok1;
let tok2;
let pair;
let route;
let trade;

class UniswapTokenPriceFetcher
{
    constructor(async_params)
    {
        async_params.forEach((element) => {
            if (element === 'undefined')
            {
                throw new Error('All parameters must be defined')
            }
        });

        this.trade = async_params[0];
        this.route = async_params[1];
        this.pair = async_params[2];
        this.tok1 = async_params[3];
        this.tok2 = async_params[4];
    }

    static async build(token1, token2)
    {
        
        var tok1 = await Fetcher.fetchTokenData(chainId, toChecksumAddress(token1))
        var tok2 = await Fetcher.fetchTokenData(chainId, toChecksumAddress(token2))
        var pair = await Fetcher.fetchPairData(tok1, tok2)
        var route = new Route([pair], tok2)
        var trade =  new Trade(route, new TokenAmount(tok2, web3.utils.toWei('1', 'Ether')), TradeType.EXACT_INPUT)
        return new UniswapTokenPriceFetcher([trade, route, pair, tok1, tok2])

    }

    getExecutionPrice6d = () =>
    {
        return this.trade.executionPrice.toSignificant(6);     
    }

    getNextMidPrice6d = () =>
    {
        return this.trade.nextMidPrice.toSignificant(6);     
    }
}




module.exports = UniswapTokenPriceFetcher

谢谢大家!

编辑:我知道 Uniswap 只与 WETH 配对,所以我的令牌变量之一是不必要的,但问题仍然存在!另外请记住,我想存储此类的一个实例以供以后在另一个文件中使用。

【问题讨论】:

  • 您能告诉我们您在调用构建静态方法时遇到的错误吗?或者用您尝试过的任何尝试更新您的答案?

标签: node.js blockchain ethereum


【解决方案1】:

您应该使用await 调用构建函数

const priceFetcher = await UniswapTokenPriceFetcher.build(token1, token2)

或后跟then

UniswapTokenPriceFetcher.build(token1, token2).then(priceFetcher => {...})

我没有看到任何其他方式。

【讨论】:

  • 在第一个解决方案上,我如何知道 priceFetcher 何时可以使用?
  • const priceFetcher = await UniswapTokenPriceFetcher.build(token1, token2) 之后的行在 priceFetcher 可用之前不会运行。因此,在下一行中,您可以确定 priceFecter 将包含由 Promise 解析的值。这就是await 的工作原理。
  • 那么在等待构建完成时调用不带 await 关键字的函数会执行下一行代码吗?
  • 是的。在没有等待的情况下调用 async 函数会返回一个 Promise 并在该 Promise 仍处于挂起状态时移至下一行。如果你把 await 放在 async 函数前面,Javascript 将继续做其他事情,直到 promise 解析出一个值。只有这样,javascript 才会将解析后的值分配给 priceFetcher 并移至下一行。
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2020-04-27
  • 2020-11-02
  • 2020-04-19
  • 2020-02-17
相关资源
最近更新 更多