Sobes.tech
Junior — Middle

How can you handle the result of a Promise to perform further actions after its completion?

sobes.tech AI

Answer from AI

To handle the result of a Promise in Node.js, the methods then, catch, and finally are used:

  • then — called upon successful completion of the Promise, accepts a function with the result.
  • catch — called when an error occurs, accepts a function with the error object.
  • finally — called in any case after the Promise is settled, regardless of the outcome.

Example:

someAsyncFunction()
  .then(result => {
    console.log('Success:', result);
    // further actions
  })
  .catch(error => {
    console.error('Error:', error);
  })
  .finally(() => {
    console.log('Promise handling completed');
  });

You can also use async/await for more convenient syntax:

async function process() {
  try {
    const result = await someAsyncFunction();
    console.log('Success:', result);
  } catch (error) {
    console.error('Error:', error);
  } finally {
    console.log('Promise handling completed');
  }
}

process();