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!
The reason is that
trans()
returns immediately because it does not block -- it performs an asynchronous request. Sotext = "";
andlang = "";
are executed before your callbacks intrans()
.An easy solution to this is to not use the "global" values and pass in the values instead:
Then change:
to:
These local variables will then shadow the "globals."