【问题标题】:How to use the result of .then function to another function in js?如何将.then函数的结果用于js中的另一个函数?
【发布时间】:2021-12-02 12:35:23
【问题描述】:

请帮助我想在函数 2 (Fn2) 中使用函数 1 (Fn1) 的结果。

App={
st: null,//st is number value

Fn1: function() {
    App.contracts.contractName.deployed().then(function(instance){
       return instance.getST();
    }).then(function(result){      
        App.st = result;    
    });
},
Fn2: function() {
       alert(App.st)//
}    
}

【问题讨论】:

    标签: javascript promise app.js


    【解决方案1】:

    您需要在Fn2 之前调用Fn1 才能访问它的值,所以让我们将Fn1 包装成Promise

    App = {
        st: null,//st is number value
    
        Fn1: function() {
            return new Promise((resolve, reject) => {
                App.contracts.contractName.deployed().then(function(instance){
                    return instance.getST();
                }).then(function(result){      
                    App.st = result;
                    resolve();
                }).catch(function(err){
                    reject(err);
                })
            })
        },
        Fn2: function() {
            alert(App.st)
        }    
    }
    

    async/await 或更好:

    App = {
        st: null,//st is number value
    
        Fn1: async function() {
            try {
                const instance = await App.contracts.contractName.deployed();
                const result = await instance.getST();
                App.st = result;
            } catch(err) {
                throw err;
            }
        },
        Fn2: function() {
            alert(App.st)
        }    
    }
    

    现在你可以等到Fn1 exec 再调用Fn2

    App.Fn1().then(function() {
      App.Fn2()
    })
    

    或使用async/await:

    await App.Fn1()
    App.Fn2()
    

    【讨论】:

    • 警告:这是嵌套的 Promise 反模式。 App.contracts.contractName.deployed() 已经返回一个承诺 - 创建另一个承诺没有意义。
    • @Quentin 这就是为什么我建议 OP 在可能的地方使用 async/await 而不是老式的承诺链/嵌套
    • @Xeelley 谢谢,这两种方法都有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2020-05-31
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多