kevinlinxp
12/31/2016 - 5:29 AM

AngularJS:Promise

AngularJS:Promise

function getById(id) {
  return $q(function (resolve, reject) {
    var editor = editorCache[id];
    if (!editor) {
      // Retrieve all the editors asynchronously.
      var promises = editorsPaths.map(function (editorsPath) {
        return $http.get(editorsPath).then(function (response) {
          var editors = response.data;
          return editors;
        });
      });

      // Wait all the asynchronous call to be resolved then return the specific editor
      $q.all(promises).then(function (arrayOfEditors) {
        arrayOfEditors.forEach(function (editors) {
          editors.forEach(function (editor) {
            editorCache[editor.id] = editor;
          });
        });
        editor = editorCache[id];
        resolve(editor);
      });
    } else {
      resolve(editor);
    }
  });
}