Saturday, January 1, 2022

Promises in javascript

A Promise is an object that represents the future result of an asynchronous operation.

Example: API call, file reading, database query.

Promise  states -

1. Pending → still waiting
2. Fulfilled → completed successfully
3. Rejected → failed

Example:

const promise = new Promise((resolve, reject) => {

let success = true;

if(success){
resolve("Task completed");
} else {
reject("Task failed");
}
});

Here:

  • resolve() → marks promise as fulfilled
  • reject() → marks promise as rejected 

    To handle the result:

    promise
    .then(result => {
    console.log(result);
    })
    .catch(error => {
    console.log(error);
    });
    • .then() → runs if success
    • .catch() → runs if error










    





No comments:

Post a Comment

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...