1

请帮助我想在函数 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)//
}    
}
4

1 回答 1

1

你需要调用Fn1beforeFn2来访问它的值,所以让我们包装Fn1Promise中:

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)
    }    
}

现在您可以等到Fn1exec 再调用Fn2

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

或使用async/await

await App.Fn1()
App.Fn2()
于 2021-12-02T12:54:56.777 回答