0

So, I've been trying to run a promise in a sync way through a generator function. I need it this way, because I have to init a particular object before the rest of the dependencies, and the function that initializes all these dependencies has to return a particular app object, but not a promise (because the damn framework utilizes this object in a synchronous way afterwards).

So, the only small async part that I have to make sync is a ping call. Here's how I've made use of the generator:

 function initLogger() {
      const pingLogServer = function* (logServerHost) {
        return ping.promise.probe(logServerHost)
          .then((res) => {
            return res;
          });
      };

      const res = yield pingLogServer(logServerHost);

      if (res.alive === true) {
         ... blah blah, do stuff to logger object

      return logger;
  }

Nevertheless, I get a syntax error:

const res = yield pingLogServer(logServerHost);
                  ^^^^^^^^^^^^^
SyntaxError: Unexpected identifier

It's the first time I'm implementing generators, and I used some tutorials (this and this), so I might as well be doing it wrong.

I'm on node v6.11.1, so I can't use async/await (unfortunately). If there are any other suggestions for implementing this - they're most welcome!

P.S. not a duplicate because it's a very narrowed-down problem/solution case, where I'm providing a big part of the solution and just looking for the end help, and I've explained why I can't use other solutions, f.e. async/await.

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
  • 1
    As far as I understand the documentation of `yield`, it is used _inside_ the generator function to return the generated object. –  Oct 05 '17 at 09:36
  • 1
    I think the one use generator is `pingLogServer` not the `initLogger` right (since only `pingLogServer` use the `function*` syntax)? Then shouldn't the `yield` be put inside of `pingLogServer` instead of in `initLogger`? – samAlvin Oct 05 '17 at 09:36
  • 1
    Trying to run async code synchronously is a bad idea. You need to accept that JavaScript is asynchronous in nature. – Liam Oct 05 '17 at 09:40
  • Where is `logServerHost` declared? – Liam Oct 05 '17 at 09:42
  • Rather than generators, you might want to look into Promise's and async / await. – Keith Oct 05 '17 at 09:44
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Oct 05 '17 at 09:46
  • @samAlvin and @Chris G - I got your point and it works now! I put the `yield` keyword in front of the `ping.promise...` call. You can post an answer and I'll accept it. :) – Milkncookiez Oct 05 '17 at 09:48
  • i can refer this question to this link : https://stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously – Denis Enrico Hasyim Oct 05 '17 at 15:02

0 Answers0