Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add progress method for promises #111

Open
fahad86 opened this issue Oct 11, 2019 · 1 comment
Open

Add progress method for promises #111

fahad86 opened this issue Oct 11, 2019 · 1 comment

Comments

@fahad86
Copy link

fahad86 commented Oct 11, 2019

Useful for use-cases like file-upload etc

Q library implementation:
`
/**

  • Attaches a listener that can respond to progress notifications from a
  • promise's originating deferred. This listener receives the exact arguments
  • passed to deferred.notify.
  • @param {Any*} promise for something
  • @param {Function} callback to receive any progress notifications
  • @returns the given promise, unchanged
    */
    Q.progress = progress;
    function progress(object, progressed) {
    return Q(object).then(void 0, void 0, progressed);
    }

Promise.prototype.progress = function (progressed) {
return this.then(void 0, void 0, progressed);
};

/**

  • Turns an array of promises into a promise for an array. If any of
  • the promises gets rejected, the whole array is rejected immediately.
  • @param {Array*} an array (or promise for an array) of values (or
  • promises for values)
  • @returns a promise for an array of the corresponding values
    */
    // By Mark Miller
    // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
    Q.all = all;
    function all(promises) {
    return when(promises, function (promises) {
    var pendingCount = 0;
    var deferred = defer();
    array_reduce(promises, function (undefined, promise, index) {
    var snapshot;
    if (
    isPromise(promise) &&
    (snapshot = promise.inspect()).state === "fulfilled"
    ) {
    promises[index] = snapshot.value;
    } else {
    ++pendingCount;
    when(
    promise,
    function (value) {
    promises[index] = value;
    if (--pendingCount === 0) {
    deferred.resolve(promises);
    }
    },
    deferred.reject,
    function (progress) {
    deferred.notify({ index: index, value: progress });
    }
    );
    }
    }, void 0);
    if (pendingCount === 0) {
    deferred.resolve(promises);
    }
    return deferred.promise;
    });
    }
    `
@suguru03
Copy link
Owner

@fahad86 Thanks for the feature idea!
Looks useful! I will investigate it. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants