简体   繁体   中英

How to create a function returning a promise that resolves after inner promise resolves

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.

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.

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.

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');
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM