0
votes

I am trying to create a wrapper function that returns a Promise object which will resolve after an inner Promise resolves. Basically, something like this:

function wrapper() {
  return new Promise((resolve, reject) => {
    MyApi.asyncCall()
      .then(data => {
        // do this first, then resolve outer promise
        resolve();
      })
      .catch(e => {
        reject();
      });
  });
}

The reason I need to do this is I have an interface that accepts a promise argument, then triggers an action once that promise resolves. I need to make an async call, then do something with the response, then trigger the interface.

Edit Explanation of purpose: I need to perform actions with the response of the inner promise BEFORE resolving the outer promise. The interface accepts an unresolved promise object, and then mounts a component when it is resolved. If I pass the inner promise it will mount before the actions on the data response are performed.

3

3 Answers

1
votes

Basically — you doing it right. You are resolve \ reject promise when you need.

But you can do it easily — simply return original promise:

function wrapper() {
  return MyApi.asyncCall()
}

So your returning promise, which resolves or rejectes when MyApi.asyncCall resolves or rejects.

If you need to do some staff inside you can do it inside this promise:

function wrapper() {
  return MyApi.asyncCall()
    .then((data) => {
      doSomeOtherStaff(data)
      return data
    })
}

Note that if you need data outside — you have to return it from your then callback inside.

0
votes

Can you explain why you need the wrapper promise exactly?

MyApi.asyncCall()
      .then(data => {
        // do this first, then resolve outer promise
        resolve();
      })
      .catch(e => {
        reject();
      });

is a promise itself, and it should be enough to just return it.

0
votes

You can use async await for the first promise and after getting data of the first promise then return the second promise :

function wrapper(){
  return new Promise( async   (resolve,reject)=>{
   let myFirstPromise =  await firestPromise();
   // do your stuff here
   console.log(myFirstPromise)
   return resolve('Second Promise');
  });
}

function firestPromise(){
  return new Promise( (resolve,reject)=>{
   return resolve('First Promise');
  });
}