JS中如何将函数内.then的执行结果传递到另一个函数中使用
问题解决思路
你当前代码无法拿到预期值的核心原因是 Fn1 中的合约操作是异步Promise任务,同步调用 Fn1 后立刻执行 Fn2 时,App.st 还未被异步回调赋值,因此只能拿到初始的null值。
方案1:Promise 链式调用(适配现有写法)
修改Fn1返回完整Promise链,调用时在异步执行完成后再触发Fn2:
App={ st: null,//st is number value Fn1: function() { // 直接返回Promise链,方便外部接续处理 return App.contracts.contractName.deployed().then(function(instance){ return instance.getST(); }).then(function(result){ App.st = result; }); }, Fn2: function() { alert(App.st) } } // 调用示例 App.Fn1().then(function() { App.Fn2(); // 此时App.st已经完成赋值 })
方案2:async/await 语法简化写法
用ES7的async/await语法让异步逻辑的写法更贴近同步逻辑,可读性更高:
App={ st: null,//st is number value Fn1: async function() { const instance = await App.contracts.contractName.deployed(); const result = await instance.getST(); App.st = result; }, Fn2: function() { alert(App.st) } } // 调用示例 async function exec() { await App.Fn1(); // 等待异步逻辑执行完成 App.Fn2(); } exec();
方案3:回调函数适配
如果你的业务场景需要回调触发,也可以给Fn1传入回调参数:
App={ st: null,//st is number value Fn1: function(callback) { App.contracts.contractName.deployed().then(function(instance){ return instance.getST(); }).then(function(result){ App.st = result; // 回调存在时执行回调 callback && callback(); }); }, Fn2: function() { alert(App.st) } } // 调用示例 App.Fn1(App.Fn2);
内容的提问来源于stack exchange,提问作者RMNA
相关产品推荐
相关产品推荐

