JavaScript Promises

PHOTO EMBED

Thu Jun 30 2022 14:47:02 GMT+0000 (Coordinated Universal Time)

Saved by @Polly

const promise = new Promise((resolve, reject) => {
  // contain an operation
  // ...

  // fake async api call and return the state
   setTimeout(() => {
      if (success) {
        resolve([
          { username: 'john', email: 'john@test.com' },
          { username: 'jane', email: 'jane@test.com' },
        ]);
      } else {
        reject('Failed to the user list');
      }
    }, 1000);
});

// after setTimeout executes -> resolve/callback with user data
getUsers().then((users) => {
  console.log(users);
});
content_copyCOPY

Resolve/Reject emulates the callback technique

https://www.javascripttutorial.net/es6/javascript-promises/