ArchNemSyS
ArchNemSyS

Reputation: 357

Javascript passing/chaining a promise using async/await

Is it possible in Javascript to await a promise that has already been sent but possibly not yet resolved ?

async function doStuff(nth) {
  setTimeout(() => console.log(nth), 2000);
}


async function waitForMe(prom, callback, nth) {
  await prom;
  await callback(nth);
}


const v = doStuff(1);
waitForMe(v, doStuff, 2);

The code above executes in parallel; for my problem the user may call doStuff at runtime again before it completes and must execute sequentially.

Upvotes: 0

Views: 76

Answers (1)

Countingstuff
Countingstuff

Reputation: 783

Can you not do like this?

function doStuff(nth) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(nth);
      resolve("done");
    }, 2000);
  });
}

async function waitForMe(prom, callback, nth) {
  await prom;
  await callback(nth);
}

const v = doStuff(1);
waitForMe(v, doStuff, 2);

Upvotes: 3

Related Questions