RMNA
RMNA

Reputation: 11

How to use the result of .then function to another function in js?

Please help I want to use the result of function 1 (Fn1) in function 2 (Fn2).

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

Upvotes: 1

Views: 80

Answers (2)

Dane Brouwer
Dane Brouwer

Reputation: 2972

You can just return the Promise defined in Fn1

Fn1: function() {
  return App.contracts.contractName.deployed().then((instance) => {
    return instance.getST();
  }).then((result) => {
    // Note that we return the assignment
    return App.st = result;
  });
}

Then you have two options, either you can call Fn1 before Fn2

App.Fn1().then(st => App.Fn2());

Or you can adjust Fn2's implementation to call Fn1 first.

// simplistic solution
Fn2: function() {
  App.Fn1().then(st => {
    // do something with st
  });
}

// more robust solution
Fn2: function() {
  const resolveST = () => App.st != null ? Promise.resolve(App.st) : App.Fn1();
  resolveST().then(st => {
    // do something with st
  })
}

Then using Fn2 is as simple as App.Fn2()

Upvotes: 0

Xeelley
Xeelley

Reputation: 1116

You need to call Fn1 before Fn2 to access it's value, so let's wrap Fn1 into 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)
    }    
}

or better with 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)
    }    
}

Now you can wait until Fn1 exec before calling Fn2:

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

or using async/await:

await App.Fn1()
App.Fn2()

Upvotes: 2

Related Questions