-1

This code i am about to put here does not work in the respect that my graphQL server always receives an empty array back... i know this is because the call completes before the data is available.. i don't have much experience with promises so i am wondering how i can get it to work, i played with a bunch of different combinations to attempt to await the response so that i could just pass back an array of id's to the playground... the browsewr.on(end) part works fine and the proper data shows in the console? Anyone care to shed some light for me?

  const browser = await lookbookIndex.browseAll();
  let hits = [];
  let returnArray = [];

  browser.on('result', (content) => {
    hits = hits.concat(content.hits);
  });

  browser.on('end', () => {
    console.log('Finished!');
    console.log('We got %d hits', hits.length);
    returnArray = hits ? hits.map(a => a.objectID) : [];
  });

  browser.on('error', err => err);

  return returnArray;
Greg Belyea
  • 858
  • 1
  • 5
  • 15

1 Answers1

1

Async syntax automatically wraps everything to Promise instance.

But you also can return Promise instance manually. It accepts callback with resolve & reject arguments. And you can call resolve to resolve the promise:

async function search() {
    const browser = await lookbookIndex.browseAll();
    return new Promise((resolve, reject) => {
        let hits = [];

        browser.on('result', (content) => {
            hits = hits.concat(content.hits);
        });

        browser.on('end', () => {
            console.log('Finished!');
            console.log('We got %d hits', hits.length);
            resolve(hits ? hits.map(a => a.objectID) : [])
        });

        browser.on('error', err => reject(err));
    })
}

And you can await the promise:

await new Promise(...)

Similar questions:

KiraLT
  • 2,385
  • 1
  • 24
  • 36
  • Thanks for the quick response, this was blocking me from accomplishing a bigger task and works great... i really appreciate it.. – Greg Belyea Nov 07 '20 at 13:42
  • If you use the promise constructor you can drop the async keyword. – Keith Nov 07 '20 at 13:48
  • Technically yes, but if you are using linting (eslint, tslint), it may require all functions which return promise to be async. – KiraLT Nov 07 '20 at 13:53
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! Put the `await lookbookIndex.browseAll();` outside of the callback – Bergi Nov 07 '20 at 14:24
  • Good point, I didn't notice that `browseAll` was an async function. – KiraLT Nov 07 '20 at 16:43