Multiple functions in Node.js

663 Views Asked by At

I have this one big multi-functional function:

 function trans() {
        var credentials = {
            clientId: 'TurboFanTrans',
            /* Client ID from the registered app */
            clientSecret: 'Gkqa2Ru37DeHAfR4AdH/sj94J5Ge1S8Ad7Spp89MMIs=' /* Client Secret from the registered app */
        };

        translator.detect(credentials, text, detectCb);

        function detectCb(err, from) {
            if (err) {
                sendMain('error', err);
                return;
            }

            translator.translate(credentials, text, from, lang, translateCb);
        }

        function translateCb(err, translated) {
            if (err) {
                sendMain('error', err);
                return;
            }

            console.log(text + lang + "=>" + translated);
        }

    }

Assume everything is declared, since its multifunctional, I am doing something wrong when I am calling trans() here is the code snippet:

case 'translate':
                        text += args[1];
                        lang += args[2];
                        trans();
                        text = "";
                        lang = "";
                        break;

When called, since its all messed up, text and lang return as empty strings(they are originally). Can anyone of you guys help me sort this out whether in code or in my brain? the end result should be the translated text of text in the language of anything in lang. Thank in advance!

1

There are 1 best solutions below

0
On BEST ANSWER

The reason is that trans() returns immediately because it does not block -- it performs an asynchronous request. So text = ""; and lang = ""; are executed before your callbacks in trans().

An easy solution to this is to not use the "global" values and pass in the values instead:

case 'translate':
  text += args[1];
  lang += args[2];
  trans(text, lang);
  text = "";
  lang = "";
break;

Then change:

function trans() {

to:

function trans(text, lang) {

These local variables will then shadow the "globals."