Home > database >  How to write await() for multiple promises in JavaScript?
How to write await() for multiple promises in JavaScript?

Time:09-08

I m trying to write await for multiple promises, instead of nested functions.

Please take a look at the below code i tried, as it will explain better than me.

var main = async () => {
  // const main_ = await Promise.all(fun1,fun2,fun3);

  // Fun 3
  const fun3 = () =>
    new Promise((resolve) => async () => {
      // console.log(1);
      return resolve(await fun2(1));
    });

  // Fun 2
  const fun2 = (value) =>
    new Promise((resolve) => async (value) => {
      value = value   1;
      // console.log(value);
      return resolve(await fun1(value));
    });

  // Fun 1
  const fun1 = () =>
    new Promise((resolve) => (value) => {
      value = value   1;
      // console.log(value);
      return resolve(value);
    });

  fun3();
};

main();

I tried console logging to debut but I m getting nothing in the console.

Any help is greatly appreciated.

CodePudding user response:

the syntax is wrong, its not new Promise((resolve) => async () => {}) with 2 arrow, but new Promise((resolve) => {}) also you can call promise function without await

var main = async () => {
  // const main_ = await Promise.all(fun1,fun2,fun3);

  // Fun 3
  const fun3 = () => new Promise(resolve => {
    //console.log(1);
    return resolve(fun2(1));
  });

  // Fun 2
  const fun2 = (value) => new Promise(resolve => {
    value = value   1;
    //console.log(value);
    return resolve(fun1(value));
  });

  // Fun 1
  const fun1 = (value) => new Promise(async (resolve) => {
    value = value   1;
    console.log('sleep 3 seconds');
    await new Promise(r => setTimeout(r, 3000));
    console.log(value);
    return resolve(value);
  });

  fun3();
};

main();

CodePudding user response:

If you want to call await inside a Promise callback, you can do this:

const p = new Promise((resolve) => {
  (async () => {
    const res = await anotherPromise();
    resolve(res);
  })();
});

So with this in mind, you can rewrite your functions like this:

var main = async () => {
  // const main_ = await Promise.all(fun1,fun2,fun3);

  // Fun 3
  const fun3 = () =>
    new Promise((resolve) => {
      (async () => {
        resolve(await fun2(1));
      })();
    });

  // Fun 2
  const fun2 = (value) =>
    new Promise((resolve) => {
      value = value   1;
      (async () => {
        resolve(await fun1(value));
      })();
    });

  // Fun 1
  const fun1 = (value) =>
    new Promise((resolve) => {
      value = value   1;
      (async () => {
        resolve(value);
      })();
    });

  return await fun3();
};

// ans: 3
console.log(await main());

If you want to do it in pure async/await, you may do this:

const main = async () => {
  const fun1 = async (value) => value   1;
  const fun2 = async (value) => await fun1(value   1);
  const fun3 = async () => await fun2(1);
  return await fun3();
}
// output: 3
console.log(await main());

CodePudding user response:

I hope this example works for you.

console.clear();

function wait(ms, data) {
  return new Promise( resolve => setTimeout(resolve.bind(this, data), ms) );
}

/** 
 * These will be run in series, because we call
 * a function and immediately wait for each result, 
 * so this will finish in 1s.
 */
async function series() {
  return {
    result1: await wait(500, 'seriesTask1'),
    result2: await wait(500, 'seriesTask2'),
  }
}

/** 
 * While here we call the functions first,
 * then wait for the result later, so 
 * this will finish in 500ms.
 */
async function parallel() {
  const task1 = wait(500, 'parallelTask1');
  const task2 = wait(500, 'parallelTask2');

  return {
    result1: await task1,
    result2: await task2,
  }
}

async function taskRunner(fn, label) {
  const startTime = performance.now();
  console.log(`Task ${label} starting...`);
  let result = await fn();
  console.log(`Task ${label} finished in ${ Number.parseInt(performance.now() - startTime) } miliseconds with,`, result);
}

void taskRunner(series, 'series');
void taskRunner(parallel, 'parallel');

CodePudding user response:

fun3() is an async function so you have to put await before the call.

var main = async () => {
  // Fun 3
  const fun3 = () => new Promise(resolve => {
    //console.log(1);
    return resolve(fun2(1));
  });

  // Fun 2
  const fun2 = (value) => new Promise(resolve => {
    value = value   1;
    //console.log(value);
    return resolve(fun1(value));
  });

  // Fun 1
  const fun1 = (value) => new Promise(async (resolve) => {
    value = value   1;
    console.log('sleep 3 seconds');
    await new Promise(r => setTimeout(r, 3000));
    console.log(value);
    return resolve(value);
  });

  await fun3();
};

main();

  • Related