0
const getLang = function (req) {
        translate.detect(req.body.phrase, function (err, res) {
            if (err) throw err;
            console.log(res);
            return res;
        });


router.post('/addPhrases', (req, res) => {
    var lang = getLang(req);
    console.log(lang);
})

console.log(lang) from second function print undefined, it runs before the first function make a return

how can I fix it?

Qwertycal
  • 21
  • 4
  • `translate.detect` is asynchronous. You have to `console.log` inside it's callback. `var lang = getLang(req)` will not wait and give you back the language. – kiddorails Jun 18 '18 at 03:35

2 Answers2

1

You can use Promises. Promises allow you to wait for async tasks to complete, using ".then" and ".catch". The ".then" is called when the Promise successfully resolves. The ".catch" is called when the Promise is rejected.

For your example you can instead do:

const getLang = function (req) {
    return new Promise((resolve, reject) => {
        translate.detect(req.body.phrase, (err, res) => {
            if (err){
                reject(err);
            } else {
                console.log(res);
                resolve(res);
            }
        });
    });
}


router.post('/addPhrases', (req, res) => {
    var lang = getLang(req).then((lang) => {
        console.log(lang);
    }).catch((error) => {
        // handle error here
        throw new Error(error);
    });
})
brad mcallister
  • 419
  • 2
  • 13
0

One of the problems is found in the fact that your getLang function doesn’t actually return anything, and so the default return value is going to be undefined. Even still, you correctly point out that getLang makes an asynchronous function call, so even if you return the value of your translation function from getLang, this will not allow you to successfully assign your variable to it unless you:

  1. wrap getLang in a promise and use async/await, or
  2. just make use of the translation value inside the callback function of translate.detect
Ben Steward
  • 2,338
  • 1
  • 13
  • 23