Daniel Stephens
Daniel Stephens

Reputation: 3209

How to call two then's from a single Promise?

I use TypeScript and given is the following code:

fooOpen("xyz").then((r) => {
    return r.getBar();
}).then((bar) => {
   console.log(bar);
});

fooOpen("xyz").then((r) => {
    return r.getBas();
}).then((bas) => {
   console.log(bas);
});

Instead of executing fooOpen('xyz') twice, is there a way how to trigger getBar and getBas from a single call of fooOpen('xyz')?

Upvotes: 0

Views: 57

Answers (2)

Marc Stroebel
Marc Stroebel

Reputation: 2357

try using await

//pseudo code...
async combineResultsFunction():Promise<[]> {

const foo = await fooOpen("xyz");

const bar = await foo.getBar();
const bas = await foo.getBas();

return Promise.resolve([bas, bar]);

}

or combine with Promise.all()

//pseudo code...
async combineResultsFunction(): ... {
 const foo = await fooOpen("xyz");
 return Promise.all(foo.getBar(), foo.getBas())
}

Upvotes: 0

Karan
Karan

Reputation: 12619

Try with returning both your desired calls in an array like [r.getBar(), r.getBas()];.

Edit As per your comment getBar & getBas are promises then you can use Promise.all() as return Promise.all([r.getBar(), r.getBas()]);

And inside then use destruction as then(([bar, bas]) => {...}.

Check complete code below.

fooOpen("xyz").then((r) => {
  return Promise.all([r.getBar(), r.getBas()]);
}).then(([bar, bas]) => {
  console.log(bar);
  console.log(bas);
});

Check output in below sample. Added foo and fooOpen for testing.

class foo {
  getBar() {
    return Promise.resolve("bar");
  }
  getBas() {
    return Promise.resolve("bas");
  }
}

function fooOpen(a) {
  return new Promise(r => r(new foo()));
}

fooOpen("xyz").then((r) => {
  return Promise.all([r.getBar(), r.getBas()]);
}).then(([bar, bas]) => {
  console.log(bar);
  console.log(bas);
});

Upvotes: 1

Related Questions