enableHandlePromises method

dynamic enableHandlePromises()

Implementation

enableHandlePromises() {
  evaluate("""
   var FLUTTER_NATIVEJS_PENDING_PROMISES = {};
    var FLUTTER_NATIVEJS_PENDING_PROMISES_COUNT = -1;

    function $REGISTER_PROMISE_FUNCTION(promise) {
      FLUTTER_NATIVEJS_PENDING_PROMISES_COUNT += 1;
      idx = FLUTTER_NATIVEJS_PENDING_PROMISES_COUNT;
      FLUTTER_NATIVEJS_PENDING_PROMISES[idx] = FLUTTER_NATIVEJS_MakeQuerablePromise(promise);
      return idx;
    }
  """);
  final fnResult = evaluate("""
    function FLUTTER_NATIVEJS_CLEAN_PROMISE(idx) {
      delete FLUTTER_NATIVEJS_PENDING_PROMISES[idx];
    }

    function FLUTTER_NATIVEJS_IS_PENDING_PROMISE(idx) {
      return FLUTTER_NATIVEJS_PENDING_PROMISES[idx].isPending();
    }

    function FLUTTER_NATIVEJS_IS_FULLFILLED_PROMISE(idx) {
      return FLUTTER_NATIVEJS_PENDING_PROMISES[idx].isFulfilled();
    }

    function FLUTTER_NATIVEJS_IS_REJECTED_PROMISE(idx) {
      return FLUTTER_NATIVEJS_PENDING_PROMISES[idx].isRejected();
    }

    /**
     * This function allow you to modify a JS Promise by adding some status properties.
     * Based on: http://stackoverflow.com/questions/21485545/is-there-a-way-to-tell-if-an-es6-promise-is-fulfilled-rejected-resolved
     * But modified according to the specs of promises : https://promisesaplus.com/
     */
    function FLUTTER_NATIVEJS_MakeQuerablePromise(promise) {
        // Don't modify any promise that has been already modified.
        if (promise.isResolved) return promise;

        // Set initial state
        var isPending = true;
        var isRejected = false;
        var isFulfilled = false;
        var value = null;

        // Observe the promise, saving the fulfillment in a closure scope.
        var result = promise.then(
            function(v) {
                isFulfilled = true;
                isPending = false;
                value = v;
                return v;
            },
            function(e) {
                isRejected = true;
                isPending = false;
                value = e;
            }
        );

        result.isFulfilled = function() { return isFulfilled; };
        result.isPending = function() { return isPending; };
        result.isRejected = function() { return isRejected; };
        result.getValue = function() { return value };
        return result;
    }
    FLUTTER_NATIVEJS_MakeQuerablePromise;
  """);

  localContext['makeQuerablePromise'] = fnResult.rawResult;
}