How is the “new promise” used in ES6?
In ES6, you can create a Promise object using new Promise(). Promises are a way of handling asynchronous operations, making the results of asynchronous code more controllable and predictable.
The new Promise() function takes a function as an argument, which contains two parameters: resolve and reject. The resolve function is used to mark the Promise as successfully completed and return the result, while the reject function is used to mark the Promise as failed and return an error message.
const promise = new Promise((resolve, reject) => {
// 异步操作
// 如果操作成功,调用resolve并传递结果
// 如果操作失败,调用reject并传递错误信息
});
A Promise object has three states: pending (in progress), fulfilled (successful), and rejected (failed). Once the Promise’s state changes to fulfilled or rejected, it is considered resolved.
You can use the .then() method to access the result of a Promise, and it takes one or two callback functions as parameters. The first callback function is used to handle successful cases, and the second callback function (optional) is used to handle failures.
promise.then(
result => {
// 处理成功的情况
},
error => {
// 处理失败的情况
}
);
Furthermore, Promise also offers some static methods such as Promise.all() and Promise.race() to handle situations involving multiple Promise objects.