简体   繁体   中英

Global variables in Javascript and how to return variables from then() JavaScript function

ShowInfo : function (number) {

        var answer
        App.contracts.StudentState.deployed().then(function (instance) {
            return instance.showFName(number);
        }).then(function (Cert) {
            answer = Cert;
        })

        console.log(answer);
        return answer;

    },

Here is the function I have been trying to perfect for too much time then I should. I am new to JavaScript and need for this function to return a variable called answer, but I always get it as undefined, I know that in JavaScript I just can't have global variables that easily, but how do I fix this code? This is linked with Ethereum smart contracts from where I receive a number.

Thank you for your time and effort.

Well these are the two code lines I'm using at the moment:

var wrapper = document.getElementById("myHTMLWrapper");

    var myHTML = '';
    for (var i = 0; i < num; i++) {
        var ans =  App.ShowInfo(i);
        myHTML += '<span class="test">INFO:' + ans + '</span><br/><br/>';
    }

    wrapper.innerHTML = myHTML
ShowInfo : function (number) {

        var answer = App.contracts.StudentState.deployed().then(function (instance) {
            return instance.showFName(number);
        })

        console.log(answer);
        return answer;

    },

Now I see the big picture :)

so..

ShowInfo : function (number) {

        var answer = App.contracts.StudentState.deployed().then(function (instance) {

     console.log(instance.showFName(number)) //this should be in [ans] later
     return instance.showFName(number); 
     //assuming that showFName returns string, not another promise

     })


        return answer; //this is still a Promise

    },

then..

var wrapper = document.getElementById("myHTMLWrapper");

    for (var i = 0; i < num; i++) {
        App.ShowInfo(i).then(function(ans){
        wrapper.innerHTML+='<span class="test">INFO:' + ans+' ('+i.toString()  + ')</span><br/><br/>';
      })

    }

Now I see that you dealing with multiple async actions what complicates think a little bit..

if you dealing with consuming multiple promises you need to decide if you want to act (in your case display result) when any of them resolves (finishes), or maybe all of them are done.

I choose to update your html at every moment when particular info is resolved. I think it should work if I did not miscalculated brackets ;)

You need to return whole promise instead of answer because your action is async. At the moment you are returning answer it is undefined. So.. As far as I understand your intentions you need to return whole App.contracts.Stude.... chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM