How to stream data using promises? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to stream data using promises? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

How can I stream data using promises.

I have two different functions in two different files. In one calls an API service and that returns a promise.

  async myPromise(){
    return new Promise((resolve, reject) => {
      callToAnAPI().then(()=>{
          resolve ("pending");
      }).then(()=>{
        resolve(callToAnotherAPI());
      })
      .catch(err=>{
          // error handling
      });
    });
  }

In another file I have a function like so:

  async myPromise2(){
    functionFromOtherFile().then((data)=>{
        // how can I get 'pending' here?
    }).then(data =>{
        // how can I get data fromncallToAnotherAPI() here?
    })
  }

I want to know that the api has been called and that it is in ‘pending’ state. How can I achieve this?

Answer

Stream is just an async iterator… So we could just use callback, much like node.js

function myPromise(cl) {
    cl(null, "pending")
    setTimeout(() => {
        cl(null, "data")
    }, 2000);
}

function myPromise2() {
    myPromise((err, data) => {
        console.log(data)
    })
}

myPromise2()
We are here to answer your question about How to stream data using promises? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji