3

I am having an issue migrating below two functions from generators to async / await. When I await the endPoints inside send(), I get the promise return value from fixedPublisher() as undefined. Am I missing anything below ?

Generators:

export function* fixedPublisher(endpoints: any): any {
  while (endpoints !== undefined) {
    yield co(function* send(): any {
      return endpoints;
    });
  }
}

function* send(publisher: any, rnd: any): any {
  const p = publisher.next();
  if (p.done) {
    throw new Error('publisher is done');
  }
  const endpoints = yield p.value;
  if (!endpoints || endpoints.length === 0) {
    throw new Error('publisher did not return endpoints');
  }
  const m = Math.max(endpoints.length - 1, 0);

  return endpoints[rnd.integer(0, m)];
}

Async / Await:

export async function fixedPublisher(endpoints: any): Promise<any> {
    return await co(endpoints);
}

function* send(publisher: any, rnd: any): any {
  const endpoints =  await (publisher);
  if (!endpoints || endpoints.length === 0) {
    throw new Error('publisher did not return endpoints');
  }
  const m = Math.max(endpoints.length - 1, 0);
  return endpoints[rnd.integer(0, m)];
}
Sergey
  • 995
  • 4
  • 14
  • 33
user2608576
  • 747
  • 2
  • 7
  • 17
  • 2
    A promise can only return once, I don't think you can `await` for more than one execution of the function you're awaiting(I don't know what the `co` definition is here). But, if that checks out, functions where you use `await` must be declared with the `async` keyword as well, meaning that your `send` function also needs an `async` in declaration(and also have to return a promise). – vfioox Nov 06 '17 at 14:37
  • You don't need `co` anymore when moving to async/await. They are doing the same job. I would guess `return await co(endpoints)` is your problem, because `co()` does not return a promise. Also, is `publisher` a promise? That must be converted to return a promise. – skylize Nov 13 '17 at 04:07

0 Answers0