Home > other >  Await two Promises in feathersJS
Await two Promises in feathersJS

Time:11-08

// users.hooks.js

const userDeletion = require('../userdeletion/userDeletion');
const triggerUserDeletion = () => {
  return async (context) => {
    const userDeletionRes = userDeletion(context);
    const userDeletionResRes = userDeletionRes(context);
    await Promise.all(
      [userDeletionResRes]
    );
  };
};

// userDeletion.js

module.exports = () => {

  return async (context) => {

    const userDeletionResult = await context.app.service('replicate').remove(
      {
        // ...
      }
    );

    const userDeletionResultData = userDeletionResult.data[0];
    console.log(userDeletionResultData);

  };
};

Above is my hook. How can I await 2 Promises, ie to call 2 services (not only the replicate service)

CodePudding user response:

You should create both promise objects, then use await Promise.all(promise1, promise2) or await Promise.allSettled(promise1, promise2) to pause until both have received data back.

By not calling await on each promise individually, you allow both requests to run in parallel, speeding up the function which relies on them both. This is more pronounced the more requests you make, but even with two requests it can halve the time spent waiting.

await Promise.all() will wait for all promises to resolve, or will throw an error as soon as any promise rejects. This is useful if you need both requests to succeed in order for program execution to continue - this way you can immediately begin error handling.

await Promise.allSettled() will wait for all promises to resolve or reject. You can then map over the list of objects returned and check the status field to determine whether they resolved or rejected. This is useful in cases where you want to have more granular error handling, or can recover from a failed request and continue with function execution.

  • Related