preface

Promise was undoubtedly a landmark change in the JavaScript world. It not only solved the problem of nested callback functions in asynchronous programming, but also laid the foundation for Async/Await.

The Promise specification was first proposed by the CommonJS community, became the ES2015(ES6) language specification, and is now arguably the preferred solution for asynchronous programming. The following article will explain the features and methods of Promise in detail for your reference. If there are any inaccuracies in the article, please correct them. Don’t say much, on the talent!

The body of the

1. Constructor Promise(excutor)

  • Excutor:
    • The Promise constructor takes an executor as an argument (excutor, which is essentially a callback function) and executes the excutor passed in immediately when the Promise constructor executes.
    • When excutor is called, resolve and reject are passed as arguments. When the resolve function is called, the Promise state changes to fulfilled. When reject is called, the Promise state changes to Rejected.
    • If excutor throws an exception internally, the Promise state changes directly to Rejected and the error object is returned as a result.
const p = new Promise((resolve, reject) = > {
  console.log("Excutor will be executed immediately.");
  resolve("This is a big pity");
  // reject(" reject ");
  // throw new Error(' rejected')
});
Copy the code

2, state,

Promise has three states:

  • **pending: ** initial state, neither success nor failure
  • Fulfilled: * * * * success
  • Rejected: failure

3. Instance method

– then(onFulfilled, onRejected)

  • Function:
    • Register onFulfilled and onRejected callback for the Promise
    • Returns a new promise, implementing the chain call
    • The new promise will resolve with the value returned by the callback function
  • Features:
    • The then method itself will automatically return a new Promise object. You can also manually return a Promise object in any (onFulfilled or onRejected) callback function
const p = new Promise((resolve, reject) = > {
  console.log("Excutor will be executed immediately.");
  resolve("This is a big pity");
});

The then method itself returns a promise
p.then()
  .then()
  .then((res) = > {
    console.log(res); // This is a big pity
  });
// The then method returns a promise via a callback
p.then(
  (res) = > {
    return new Promise((resolve, reject) = > {
      resolve("OnFulfilled Promise");
    });
  },
  (reason) = > {
    return new Promise((resolve, reject) = > {
      resolve("You can return Promise in the onRejected callback.");
    });
  }
).then((res) = > {
  console.log(res);
});
Copy the code
  • The then method can implement chained calls through the return Promise object
  • If the callback returns a normal value, it will be received as the callback argument in the next THEN
  • If the callback returns a Promise, the next THEN method will wait for the Promise execution to end and receive the Promise execution result
const p2 = new Promise((resolve, reject) = > {
  console.log("Excutor will be executed immediately.");
  resolve("This is a big pity");
});
p2.then(res= > {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve('Promise fulfilled')},1000);
  })
}).then(res= > {
  console.log(res)// Wait 1 second, output: Promise completed
})
Copy the code
  • If no callback function is passed in, Promise automatically registers the callback function for the THEN method and returns the received value in the callback function, passing it to the next THEN, achieving value penetration.
No callback was registered for THEN, value penetration occurredconst p3 = new Promise((resolve, reject) = > {
  resolve(1);
});
p3.then(2).then(4).then(console.log); / / 1

Copy the code
  • The then method does not allow a promise object that it returns as a return value
const p4 = p3.then(res= > {
  // If not allowed, an error will be reported
  // TypeError: Chaining cycle detected for promise #<Promise>
  return p4
})

Copy the code

– catch(onRejected)

  • role
    • Add the onRejected callback to the Promise
  • features
    • Return a new Promise
    • The new Promise will resolve with the value returned by the callback function
const promise = new Promise((resolve, reject) = > {
  reject(100);
});
promise
  .catch((reason) = > {
    console.log(reason); / / 100
    return 200; // The catch function returns the value as the resolve result of the new Promise
  })
  .then((res) = > {
    // The new Promise executes the result
    console.log(res); / / 200
  });
Copy the code

– finally(finallyCallback)

  • role
    • Add an event-handling callback to the Promise
  • features
    • The passed finallyCallback is called on success or failure
    • FinallyCallback returns a new Promise
    • The Promise execution result cannot be retrieved internally by finallyCallback
const promise = new Promise((resolve, reject) = > {
  resolve(100);
});
promise
  .finally((res) = > {
    console.log("Finally callback is always executed whether it succeeds or fails.");
    No promise execution result is available in the finally callback
    console.log(res);
  })
  .then((res) = > {
    The finally callback returns a new promise that implements the chained call
    console.log(res);
  });

Copy the code

4. Static methods

– Promise.all(promiseArray)

  • Function:
    • Takes an array as an argument and returns the execution results in array order
    • Execute the Promise objects in the array concurrently
  • Features:
    • You take an array as an argument, and the array elements can be normal values or promise objects
    • The result is returned as an array of elements that correspond to the incoming promiseArray
    • If the array element is a normal value, place the value in the result array as is
    • If the array element is a Promise object, the corresponding Promise object is executed concurrently, waiting for the execution to end, and the result is returned
const promise1 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p1");
  }, 2000);
});
const promise2 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p2");
  }, 1000);
});

const promiseAll = Promise.all([1.2, promise1, 3.4, promise2, 5]);
promiseAll.then((res) = > {
  // Execute promise concurrently
  // The result corresponds to the array passed in
  // The result will be returned after all tasks are completed
  console.log(res); / / [1, 2, "p1", 3, 4, "p2", 5]
});
Copy the code
  • If any item in the passed array fails to execute, the Promise will fail to execute
const promise1 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p1");
  }, 2000);
});
const promise2 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    reject('I'm so damn gentle, I failed to execute.')},1000);
});

const promiseAll = Promise.all([1.2, promise1, 3.4, promise2, 5]);
promiseAll.then((res) = > {
  // If any task fails, the entire promise fails
  console.log(res);
}).catch(e= > {
  // Failure of any task will result in failure of the entire Promise execution
  console.log('fail',e)
});

Copy the code

– Promise.allSettled(promiseArray)

The informal version, currently in stage4, is not yet fully supported by browsers

  • Function:
    • With the Promise. All
  • Features:
    • Wait for all tasks in the array to complete and return an array
    • Success or failure will return a result
    • Other with Promise. All
const promise1 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p1");
  }, 2000);
});
const promise2 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    reject("I'm so damn gentle, I failed to execute.");
  }, 1000);
});

const promiseAll = Promise.allSettled([1.2, promise1, 3.4, promise2, 5]);
promiseAll
  .then((res) = > {
    [{status: 'depressing ', value: 1}, {status:' depressing ', value: 2}, {status: 'depressing ', value: 2}, {status:' depressing ' 'fulfilled', value: 'p1' }, { status: 'fulfilled', value: 3 }, { status: 'fulfilled', value: 4 }, { status: This is a pity, {status: 'pity ', value: 5}] */
    console.log(res);
  })
  .catch((e) = > {
    console.log("fail", e);
  });

Copy the code

– Promise.race(promiseArray)

  • role
    • Take an array and execute the tasks in the array concurrently
    • Whoever executes the block returns the result, whether it succeeds or fails
    • Generally used for network timeout function
const promise1 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p1");
  }, 2000);
});
const promise2 = new Promise((resolve, reject) = > {
  setTimeout(() = > {
    resolve("p2");
  }, 1000);
});
const promise3 = new Promise((resolve, reject) = > {
  // Assume network timeout after 500 ms
  setTimeout(() = > {
    reject("I'm out of time");
  }, 500);
});

const promiseRace = Promise.race([promise1, promise2, promise3]);
promiseRace
  .then((res) = > {
    console.log(res);
  })
  .catch((e) = > {
    // Return whoever executes the block
    console.log("fail", e);
  });

Copy the code

– Promise.reject(reason)

  • Function:
    • Return a Promise with a failed state and pass the failure information to the corresponding handler
Promise.reject("rejected")
  .then((res) = > {
    console.log('value', res);
  })
  .catch((reason) = > {
    // reason rejected
    console.log('reason', reason);
  });

Copy the code

– Promise.resolve(value)

  • Function:
    • Accept a value and return a Promise
  • Features:
    • If value is a normal value, the normal value is used as the resolve result of the new Promise
    • If value is a Promise, the value is returned as is
Promise.resolve(100).then((res) = > {
  console.log(res); / / 100
});

const promise = new Promise((resolve, reject) = > {
  reject(200);
});
promise
  .then((res) = > {
    console.log(res); / / 200
  });

Copy the code

conclusion

That concludes the use of Promise. Thank you for reading and I hope it’s helpful. Say what you think in the comments section and let’s discuss it and make progress together. After understanding how Promise is used, in the next article, I will further explain the core principles of Promise through handwritten source code.