aacerox / node-rest-client

REST API client from node.js
MIT License
377 stars 132 forks source link

Use a loop? #205

Open robross0606 opened 5 years ago

robross0606 commented 5 years ago

I am absolutely baffled on how to use this client in a do..while loop. It appears the client does an async call, but I cannot seem to get it to await response before continuing.

async function test() {
  let doMore = true;
  do {
    let endpoint = `${share_api}/test/search/scopes/conceptId?start=${start}&pageSize=${pageSize}`;
    console.log(`Retrieving from ${endpoint}...`);
    let oldStart = start;
    await client
      .get(endpoint, args, (data, response) => {
        let values = data.values;
        let total = data.total;
        //   values.forEach(value => {
        //     console.log(value);
        //   });
        console.log(`Received ${values.length} result(s).`);
        doMore = data.hasMore;
        start += pageSize;
      })
      .on("error", function(err) {
        console.log("Something went wrong on the request", err.request.options);
        doMore = false;
      });
    doMore = oldStart < start;
    console.log("Got here.");
  } while (doMore);
}
JL102 commented 2 years ago

Try "promisifying" your retrieval and callback logic: https://javascript.info/promisify

Pseudo code:


async function test() {
  while(condition) {
    try {
      await promisify();
    } catch {..}
  }
}

function promisify() {
  return new Promise((resolve, reject) => {
    client.get(params, (data, response) => {
      // do stuff
      resolve();
    }).on('err', reject);
  }
}