Home:ALL Converter>Multiple functions with JavaScript promises

Multiple functions with JavaScript promises

Ask Time:2016-04-07T05:05:52         Author:

Json Formatter

Goal:

Using JavaScript promises, on load(), if the database is not already populated, seed it with data, then display the data with getWidgets(), otherwise, if the db is already seeded just getWidgets().

The code:

const initialWidgets = [
  {id: 1, color: 'Red', sprocketCount: 7, owner: 'John'},
  {id: 2, color: 'Taupe', sprocketCount: 1, owner: 'George'},
  {id: 3, color: 'Green', sprocketCount: 8, owner: 'Ringo'},
  {id: 4, color: 'Blue', sprocketCount: 2, owner: 'Paul'}
];

require('./model');
const Widget = require('mongoose').model('WidgetModel');

function seedWidgets() {
  let results = [];
  Widget.find({}, function (err, collection) {
    if (err) { throw err;}

    if (collection.length === 0) {
      initialWidgets.map(widget => {
        Widget.create(widget);
      });
    }
  })
}

export function getWidgets(req) {
  let widgets = req.session.widgets;
  if (!widgets) {
    /// ?? seed database  
   /// ?? add new records to session
  }
  return widgets;
}

export default function load(req) {
  return new Promise((resolve, reject) => {
    resolve(getWidgets(req));
  })
}

What would be the proper way to handle these three methods with promises when in load() ...

  1. seed database if not already populated
  2. add the records to session
  3. display session objects

Thanks

Author:,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/36462335/multiple-functions-with-javascript-promises
yy