tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

promise.js (2010B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 "use strict";
      5 
      6 loader.lazyRequireGetter(
      7  this,
      8  "generateUUID",
      9  "resource://devtools/shared/generate-uuid.js",
     10  true
     11 );
     12 loader.lazyRequireGetter(
     13  this,
     14  ["entries", "executeSoon", "toObject"],
     15  "resource://devtools/shared/DevToolsUtils.js",
     16  true
     17 );
     18 
     19 const PROMISE = (exports.PROMISE = "@@dispatch/promise");
     20 
     21 function promiseMiddleware({ dispatch }) {
     22  return next => action => {
     23    if (!(PROMISE in action)) {
     24      return next(action);
     25    }
     26    // Return the promise so action creators can still compose if they
     27    // want to.
     28    return new Promise((resolve, reject) => {
     29      const promiseInst = action[PROMISE];
     30      const seqId = generateUUID().toString();
     31 
     32      // Create a new action that doesn't have the promise field and has
     33      // the `seqId` field that represents the sequence id
     34      action = Object.assign(
     35        toObject(entries(action).filter(pair => pair[0] !== PROMISE)),
     36        { seqId }
     37      );
     38 
     39      dispatch(Object.assign({}, action, { status: "start" }));
     40 
     41      promiseInst.then(
     42        value => {
     43          executeSoon(() => {
     44            dispatch(
     45              Object.assign({}, action, {
     46                status: "done",
     47                value,
     48              })
     49            );
     50            resolve(value);
     51          });
     52        },
     53        error => {
     54          executeSoon(() => {
     55            try {
     56              dispatch(
     57                Object.assign({}, action, {
     58                  status: "error",
     59                  error: error.message || error,
     60                })
     61              );
     62            } finally {
     63              // Ensure rejecting the original promise,
     64              // even if the "error" action also throws
     65              reject(error);
     66            }
     67          });
     68        }
     69      );
     70    });
     71  };
     72 }
     73 
     74 exports.promise = promiseMiddleware;