How can I queue uploads with the Bytescale JavaScript SDK?

You can queue uploads made using the Bytescale JavaScript SDK with a simple wrapper class, which helps to increase reliability when uploading multiple files.

Instructions

Add the following code at the start of your web app (so that it runs once).

/**
 * Usage:
 * 
 * const queue = new Queue(2);
 * 
 * // Uploads will be queued after 2 concurrent uploads.
 * const result = await queue.enqueue(async () => uploadManager.upload({ 
 *   data: "Test!" 
 * }));
 *
 * console.log(result.filePath);
 */
class Queue {
  constructor(concurrency) {
    this.concurrency = concurrency;
    this.tasksRunning = 0;
    this.queue = [];
  }

  /**
   * See usage instructions above.
   */
  enqueue(task) {
    const runNext = () => {
      while (this.tasksRunning < this.concurrency && this.queue.length > 0) {
        const next = this.queue.shift();
        this.tasksRunning++;
        next().finally(() => {
          this.tasksRunning--;
          runNext();
        });
      }
    }

    return new Promise((resolve, reject) => {
      this.queue.push(() => task().then(resolve, reject));
      runNext();
    });
  }
}

Example usage

To use the above class to queue your file uploads:

// ————————————
// Run this code ONCE at the start of your app:

const queue = new Queue(2);

const uploadManager = new Bytescale.UploadManager({ apiKey: "free" });

async function myUploadFunction(someFileData) {
  return await queue.enqueue(async () => uploadManager.upload({
    // Docs: https://www.bytescale.com/docs/sdks/javascript
    data: someFileData // String, Blob, Buffer, etc.
  }));
}
// —————————————

// —————————————
// Run this code to upload files:

const { filePath } = await myUploadFunction("Hello World!")
// —————————————

Recommendations:

By queueing your file uploads, you will increase the stability and reliability of your web app:

  • Pass 2 to new Queue(2) to limit concurrency to 2 uploads.
  • Higher numbers will cause local network congestion and additional browser overhead, which can cause uploads to fail.
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us