bartve / disconnect

An easy to use Node.js client with OAuth support to connect with the discogs.com API v2.0
MIT License
453 stars 79 forks source link

How to deal with rate limit using async await ? #61

Open hems opened 4 years ago

hems commented 4 years ago

I saw the callback signature brings back the rateLimit information, but what about users using async/await?

any chance of getting that information?

thank you!

bartve commented 4 years ago

Don't have any experience with this myself, but disconnect can also return a Promise and can be used as a function for await if I understand this correctly https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

askdesigners commented 1 year ago

a TryCatch block will catch errors from async function calls, so maybe you need to handle it there? Maybe it's in the error?

jch254 commented 6 months ago

You can do something similar to this:

const getListingAsync = async (discogsClient: DiscogsClient, id: number): Promise<UserTypes.Listing> => {
  return new Promise(async (resolve, reject) => {
    discogsClient.marketplace().getListing(id, (err, data, rateLimit) => {
      if ((err && err !== null)) {
        err.rateLimit = rateLimit
        reject(err);
      } else if (data === null) {
        reject(err)}
      else {
        resolve(data);
      }
    });
  });
}

And use the getListingAsync func as below:

    try {
      const listing = await getListingAsync(discogsClient, parseInt(id, 10));

      console.log("FETCHED DISCOGS MARKETPLACE LISTING", {
        id,
        listing,
      });

      return listing;
    } catch (error: any) {
      console.log(error)
    }

The caught error will look something like:

{
  err: DiscogsError: Unknown error.
      at IncomingMessage.passData (/Users/xxx/node_modules/disconnect/lib/client.js:215:23)
      at IncomingMessage.emit (node:events:531:35)
      at IncomingMessage.emit (node:domain:488:12)
      at endReadableNT (node:internal/streams/readable:1696:12)
      at processTicksAndRejections (node:internal/process/task_queues:82:21) {
    statusCode: 429,
    rateLimit: { limit: 60, used: 65, remaining: 0 }
  },

Hope it helps