franciscop / translate

:sa: Translate text on node.js and the browser with promises
MIT License
288 stars 44 forks source link

How to return translated word instead of console log? #12

Closed joge17 closed 5 years ago

joge17 commented 5 years ago

I am trying to return the translated word from the function translateWord. When I do console.log(val) inside of then() I get the correct translated word. But when I do return val; I get undefined.

This logs the translated word to the console:

translateWord(word) {
    let promise = translate(word, 'es');
    promise.then((val) => {
      console.log(val);
    })
}

This returns undefined:

  translateWord(word) {
    let promise = translate(word, 'es');
    promise.then((val) => {
      return val;
    })
}

How can I return the translated word from the translateWord function?

franciscop commented 5 years ago

Since it is an asynchronous operation, you cannot return the plain value. With promises you'd have to use await. Please read this amazing article: