[Vuejs]-Add an undefined method promise to an array to be resolved later in Promise.all()

0👍

I solved my queue issue, but it wasn’t at all how I was trying to go about it.

My first problem was thinking that Promise.all() deferred calling my methods until it was called, but they are called when added to the array. This caused the error I mentioned in my question. So I needed to rethink how to populate the queue with methods that may not yet exist.

The solution was to add the calls to an array (the queue) as strings (e.g. "getDocs"), then loop through the array calling the methods using bracket notation (e.g. db["getDocs"]()).

My app is written in Vue.js so it’s obviously different, but here’s a simplified, working example:

// Dummy DB object
var db = {
  docs: [1, 2, 3]
};

// Queue were the DB ops are stored
var dbQueue = [];

// Process the queue - called elsewhere once the DB is connected
// The processed array and Promise.all() aren't necessary as you could just call
// the method outright, but I want to log the results in order
async function processQueue() {
  var processed = []; // Called queue methods

  // Add valid methods to
  dbQueue.forEach(method => {
    if (typeof db[method] === "function") {
      return processed.push(db[method]());
    } else {
      console.error(`"${method}" is not a name of a valid method.`);
    }
  });

    // Log promise results
  await Promise.all(processed).then(res => {
    console.log("Processed:", res);
  });

  // Empty the queue
  dbQueue = [];
}

// Add some calls to the queue of methods that don't yet exist
dbQueue.push("getDocs");
dbQueue.push("getDocs");

// Simulate adding the method
db.getDocs = function() {
  return new Promise(resolve => {
    resolve(this.docs);
  });
};

// Process queue once conditions are met (e.g. db is connected); called elsewhere
processQueue();

And here’s a fiddle with an example that allows arguments for the methods: https://jsfiddle.net/rjbv0284/1/

0👍

You can make a promise in your db module instead of just localDb property:

let localDb = null;
let resolveLocalDb = null;
let localDbPromise = new Promise(function(resolve, reject) {
    resolveLocalDb = resolve;
});

var db = {
  getLocalDb: () {
    return localDbPromise;
  }
  connectLocal: (dbName) => {
    // Do stuff
    localDb = new PouchDB(dbName) // has a allDocs() method
    resolveLocalDb(localDb);
  }
}

Then, exchange .localDb to getLocalDb(), which returns a promise.

dbQueue.push(
  db.getLocalDb().then(db => db.allDocs())
)

Leave a comment