Noah Rolf
Noah Rolf

Reputation: 57

Sequential async await calls aren't calling properly

I'm trying to beter understand promises and I dont understand why this doesnt work.

async function fooTheBar(a) {
  const b = await Foo(a);
  const c = await Bar(b);
  const d = await fooBar(c);
  return {foooo: d};
}

in live practice await bar(b) is running before b is finished being defined by await Foo(a). All of the functions are written as async and they all return data.

Upvotes: 1

Views: 61

Answers (1)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

May be you can work around with below code

function Foo(param){
  return new Promise(function(resolve, reject) {
    resolve(param);
  });
}

function Bar(param){
  return new Promise(function(resolve, reject) {
    resolve(param);
  });
}

function fooBar (param){
  return new Promise(function(resolve, reject) {
    resolve(param);
  });
}

async function fooTheBar(a) {
  const b = await Foo(a);
  const c = await Bar(b);
  const d = await fooBar(c);
  return {foooo: d};
}

fooTheBar("foo").then((resp)=>{  console.log(resp)})

Upvotes: 1

Related Questions