ttncrch
ttncrch

Reputation: 7253

chain promise and functions

I want to do a sort of Worker that executes a list of functions that can be promises or not. For that Worker, I use promise. Here is a exemple:

class PromiseChainer {

  constructor() {
    this.promise = Promise.resolve();
  }

  addToChain(f) {
    this.promise = this.promise.then(() => Promise.resolve(f));
  }

  getPromise() {
    return this.promise;
  }

}

I want to easly add functions or promises to the chain and be sure theses function will be executed synchronously.

I tested with 2 functions:

const p = new Promise(resolve => 
                      setTimeout(() => resolve(console.log('promise resolved')), 500));

const f = () => console.log('value resolved')

And finally I've a:

const promiseChainer = new PromiseChainer();

promiseChainer.addToChain(f);
promiseChainer.addToChain(p);

promiseChainer.getPromise().then(() => {
  console.log('finished');
});

in order to test if my functions are executed in the right order.

The problem is: I can't get this code working with Promises and Functions :

addToChain(f) {
  this.promise = this.promise.then(() => Promise.resolve(f));
}

Works only with Promise (Value resolved is never displayed)

addToChain(f) {
  this.promise = this.promise.then(() => f);
}

Works only with Promise (Value resolved is never displayed)

addToChain(f) {
  this.promise = this.promise.then(f);
}

Works only with Functions (Promise is resolved after the message: finished).

There is a way to accomplish that I want without a if on the type of the parameter ?

Here is my playground: https://jsbin.com/vuxakedera/edit?js,console

Thanks

Upvotes: 2

Views: 131

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You're over complicating something very simple - Promises chain directly, there is no need to try to do something like what you have implemented with PromiseChainer

const p = new Promise(resolve => 
                      setTimeout(() => resolve(console.log('promise resolved')), 500));

const f = () => console.log('value resolved')

var chain = Promise.resolve()
              .then(f)
              .then(() => p)
              .then(() => {
                  console.log('finished');
               });

Upvotes: 2

Related Questions