2

I have the following helper function

userExist(email) {
    this.findUserByEmail(email).then(result => {
      return true;
    }).catch(error => {
      return false;
    });

  }

then I call this in a different file:

var stuff = userService.userExist('abc')
console.log(stuff);

But stuff is always undefined since the function is a promise, how can I wait for this value to my helper function returns true or false

Beto
  • 806
  • 3
  • 12
  • 33

2 Answers2

3

Not having a Thenable is not possible in most cases. Promises are object that represent asynchronous work. If you were to wait for that job to complete by waiting, everything would be frozen because JS usually runs in an environment that are single-threaded.

If you want to code in an environment that ressembles synchronous programming for async stuff, try the async / await syntax. I like it a lot. Basically, it would look like this:

async function checkUserExists() {
  const exists = await userService.userExists('abc')
  console.log('Exists', exists)
}

You need to realize that promises are still used under the hood. Babel and Typescript both support this syntax now for backward compatibility with ES5. As per Node, it has support since 7.6.

gretro
  • 1,934
  • 15
  • 25
  • This syntax does _not_ use [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators) under the hood, only [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Please do not misinform in your answer. – Patrick Roberts Sep 24 '17 at 04:06
  • The Babel implementation makes use of them when transpiling. Forgive my confusion. – gretro Sep 24 '17 at 04:18
  • It does so out of convenience and necessity due to userland restrictions, not because the specification dictates so. It _looks_ similar to generator functions, but in v8 and other engines, generator functions are not used to implement async functions. – Patrick Roberts Sep 24 '17 at 04:21
  • Do you have a source on that? Some articles on the subject seem to suggest the feature is implemented that way. – gretro Sep 24 '17 at 04:22
  • Not an authoritative one off-hand, but [some pseudo-polyfills such as `asyncawait`](https://github.com/yortus/asyncawait#2-featuregotcha-summary) do not use generators at all in their source, which means that native implementations do not _need_ to use generator functions either. If you can find those articles you're referring to that suggests async is implemented on generators, I'd love to see them. – Patrick Roberts Sep 24 '17 at 04:27
  • 1
    I read a bit more. It also seems like the `async / await` implementation is faster than the generators. Thanks for the correction. – gretro Sep 24 '17 at 04:34
1

Use the then method to attach a callback that will be called once the promise resolves:

userService.userExist('abc').then(stuff => {
  console.log(stuff);
})
nem035
  • 34,790
  • 6
  • 87
  • 99