-2

I am trying to create a named promise chain. I am not sure of how to achieve this. The goal is following:

        function multiplepromises() {
            var prom = function (resolve, reject) {
                var lifecycleeventone = new someEvent();
                var lifecycleeventtwo = new someEvent();
                var lifecycleeventthree = new someEvent();
                var lifecycleeventfour = new someEvent();
                var lifecycleeventfive = new someEvent();

                lifecycleeventone.on(function () {
                    try {
                        resolve("eventone")
                    } catch {
                        reject("eventone")
                    }
                })
                lifecycleeventtwo.on(function () {
                    try {
                        resolve("eventtwo")
                    } catch {
                        reject("eventtwo")
                    }
                })
                lifecycleeventthree.on(function () {
                    try {
                        resolve("eventthree")
                    } catch {
                        reject("eventthree")
                    }
                })
                lifecycleeventfour.on(function () {
                    try {
                        resolve("eventfour")
                    } catch {
                        reject("eventfour")
                    }
                })
                lifecycleeventfive.on(function () {
                    try {
                        resolve("eventfive")
                    } catch {
                        reject("eventfive")
                    }
                })
                maineventlikefinallySOcalledalways.on(function(){
                    try {
                        resolve("maineventlikefinallySOcalledalways")
                    } catch {
                        reject("maineventlikefinallySOcalledalways")
                    }
                })
            }
            return prom
        }
        
        multiplepromises()
        .onlifecycleeventoneAsProm((result)=> result) //eventone promise resolve
        .onlifecycleeventoneerrorAsProm((error)=> error) //eventone
        .onlifecycleeventtwoAsProm((result)=> result) //eventtwo promise resolve
        .onlifecycleeventtwoerrorAsProm((error)=> error) //eventtwo
        .onlifecycleeventthreeAsProm((result)=> result) //eventthree promise resolve
        .onlifecycleeventthreeerrorAsProm((error)=> error) //eventthree
        .onlifecycleeventfourAsProm((result)=> result) //eventfour promise resolve
        .onlifecycleeventfourerrorAsProm((error)=> error) //eventfour
        .onlifecycleeventfiveAsProm((result)=> result) // eventfive promise resolve
        .onlifecycleeventfiveerrorAsProm((error)=> error) //eventfive
        .then((result)=> result) // maineventlikefinallySOcalledalways promise resolve
        .error((error)=> error) // maineventlikefinallySOcalledalways promise reject
        

    multiplepromises()
            .onlifecycleeventoneAsProm((result)=> result) //eventone promise resolve
            .onlifecycleeventoneerrorAsProm((error)=> error) //eventone
            .onlifecycleeventtwoAsProm((result)=> result) //eventtwo promise resolve
            .onlifecycleeventtwoerrorAsProm((error)=> error) //eventtwo
            .onlifecycleeventthreeAsProm((result)=> console.log("test")) 
// lifecycleeventthree promise reject stops here and 
// doesnt continue to .then/.error since there was no return from this lifecycle event(promise)
    

I have read this and this doesnt solve the purpose completely. Handling multiple catches in promise chain and https://javascript.info/promise-chaining

Dont want to use Rx and want to keep to vanilla js

Gary
  • 2,293
  • 2
  • 25
  • 47
  • what is `oneventoneAsProm` and `oneventoneerrorAsProm` etc functions? – Jaromanda X Sep 02 '20 at 04:19
  • 1
    also, your `multipromises` code is going to attempt to resolve/reject the single promise more than once ... this is not possible ... once a promise is resolved or rejected, it can not be resolved or rejected again – Jaromanda X Sep 02 '20 at 04:20
  • @JaromandaX No they are resolve reject of an event. eventtwo.on(function () { try { resolve("eventtwo") } catch { reject("eventtwo") } }) – Gary Sep 02 '20 at 04:21
  • also your try/catch will never fail, since the `resolve` function won't fail, therefore the code makes no sense – Jaromanda X Sep 02 '20 at 04:22
  • so, only one event in that list of events will ever fire? never more than one? because events don't `resolve/reject` ... they are resolving (and will never reject for the above reason) the one single promise created at the top of the code – Jaromanda X Sep 02 '20 at 04:22
  • @JaromandaX `function asyncFunc() { const eventEmitter = { success: [] }; setTimeout(() => { // (A) for (const handler of eventEmitter.success) { handler('DONE'); } }, 100); return eventEmitter; } asyncFunc() .success.push(x => console.log('Result: '+x));` This is what I want to achieve somewhat but this ".success" has to be a promise not an event. Unsure if i am talking junk. But I want to know if that is possible or I will unnecessarily complicate the code – Gary Sep 02 '20 at 04:23
  • @JaromandaX No all events will happen. But the maineventlikefinallySOcalledalways promise will be the one that needs to be captured in the promise `then` and `.error`. The other events `eventone` etc will be optional captures during the lifecycle of the code/set of actions – Gary Sep 02 '20 at 04:24
  • 2
    Then your code is flawed, as a promise can only be resolved ONCE - you have a single promise, and your code will attempt to resolve that promise more than once – Jaromanda X Sep 02 '20 at 04:24
  • your code in the comment makes even less sense ... where is `asyncFunc().success` even defined? – Jaromanda X Sep 02 '20 at 04:26
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220831/discussion-between-gary-and-jaromanda-x). – Gary Sep 02 '20 at 04:26
  • Unfortunately, your code is so sparse in detail, it doesn't help describe your requirements either ... please try to describe what you want your code to achieve – Jaromanda X Sep 02 '20 at 04:27
  • I just updated the code for the requirements. Probably, this is cleaner to understand – Gary Sep 02 '20 at 04:36
  • 3
    no, it isn't, since you're code will still attempt to resolve the same promise multiple times AND you have the pointless try/catch blocks, since nothing in try will throw - and changing the names of nonexistent properties of that function from `oneventoneAsProm ` to `onlifecycleeventoneAsProm` doesn't clarify a thing - those functions don't exist ... what are they meant to do? – Jaromanda X Sep 02 '20 at 04:38

1 Answers1

3

You can‘t achieve something like that with Promises.
Instead you can make a function that returns an object with event registrar functions, which return again the object.

Here is a simple example:

function test() {
  return new (function() {
    this.eh = {};
    
    this.on = (event, handler) => {
      this.eh[event] = handler;
      return this;
    }
    
    this.call = (event, ...args) => {
      if (typeof this.eh[event] === 'function') {
        this.eh[event](...args);
      }
    }
    
    Promise.resolve().then(() => {
      // Do your stuff...
      
      // Example:
      this.call('msg', 'This is a message.');
      setTimeout(() => {
        this.call('some-event', 'This is some event data.');
        
        this.call('error', 'This is an error.');
      }, 1000);
      
    });
  })()
}

test()
  .on('msg', (msg) => console.log(`Message: ${msg}`))
  .on('some-event', (data) => console.log(`Some event: ${data}`))
  .on('error', (err) => console.log(`Error: ${err}`))

I hope that‘s what you were up to.

Edit:
Here's another attempt: https://jsfiddle.net/bg7oyxau/

garzj
  • 2,427
  • 2
  • 8
  • 15
  • Awesome get the point. What do I do with browsers? Register a event as well? I am in the browser environment. I know I can achieve this with rxjs lite to somewhere near but just want to avoid that. Second just want to know if I convert each event into a promise using the topromise util? Tried that? Will that ever work? – Gary Sep 16 '20 at 15:43
  • @Gary No, that won't work. Why do you even want a promise? You are confusing me... – garzj Sep 16 '20 at 18:03
  • Hmm.. right that confused me as well a little. But all the events are lifecycle events. if there is return value (in resolve or reject) the next event in event chain continues. Else it stops. `lifecycleeventthree promise reject stops here and doesnt continue to .then/.error since there was no return from this lifecycle event(promise)` Pls check the second `multiplepromises()` implement. Is that even possible or I am trying something impossible? Logically: what I am trying is just a `next()` tick for the next event chain whether an error or completion in the previous lifecycle event – Gary Sep 17 '20 at 11:26
  • Probably, I am being stupid here, on a second thought. I have seen sequential lifecycle events though. Possibly I am just mixing promises and events unnecessarily – Gary Sep 17 '20 at 11:40
  • My second goal was to have a name instead of `.on` for an event implement. Is that possible? I have seen function subject implements not ones that are events – Gary Sep 17 '20 at 11:42
  • {"funcname":function} function subobject i mean – Gary Sep 17 '20 at 12:32