不知道的Promise高级用法


Promise是JavaScript中处理异步操作的一种机制,通过Promise可以更好地处理回调地狱(callback hell)和提供更为清晰的异步代码结构。以下是一些Promise的高级用法:

1. Promise Chaining(Promise链式调用)

通过返回新的Promise,可以使多个异步操作按顺序串联起来:

function asyncTask1() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("Task 1");
            resolve("Task 1 result");
        }, 1000);
    });
}

function asyncTask2(data) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("Task 2 with data:", data);
            resolve("Task 2 result");
        }, 1000);
    });
}

asyncTask1()
    .then(result => asyncTask2(result))
    .then(finalResult => console.log("Final result:", finalResult))
    .catch(error => console.error(error));

2. Promise.all()

Promise.all()接收一个Promise数组,当所有的Promise都被成功解析后,返回一个新的Promise:

const promise1 = Promise.resolve("Promise 1");
const promise2 = new Promise(resolve => setTimeout(() => resolve("Promise 2"), 1000));
const promise3 = Promise.reject("Promise 3");

Promise.all([promise1, promise2])
    .then(results => console.log(results))
    .catch(error => console.error(error));

// Output after 1 second: ["Promise 1", "Promise 2"]

3. Promise.race()

Promise.race()接收一个Promise数组,当其中任何一个Promise被解析或拒绝后,返回一个新的Promise:

const promise1 = new Promise(resolve => setTimeout(() => resolve("Promise 1"), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve("Promise 2"), 500));

Promise.race([promise1, promise2])
    .then(result => console.log(result))
    .catch(error => console.error(error));

// Output after 500 milliseconds: "Promise 2"

4. Promise.any() (Node.js 16+)

Promise.any()接收一个Promise数组,当其中任何一个Promise被解析后,返回一个新的Promise:

const promise1 = new Promise((resolve, reject) => setTimeout(() => reject("Promise 1"), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve("Promise 2"), 500));

Promise.any([promise1, promise2])
    .then(result => console.log(result))
    .catch(errors => console.error(errors));

// Output after 500 milliseconds: "Promise 2"

5. Promise.prototype.finally()

finally()方法在Promise被解析或拒绝后都会执行,无论Promise的状态如何,都能够执行一些清理操作:

asyncTask1()
    .then(result => asyncTask2(result))
    .catch(error => console.error(error))
    .finally(() => console.log("Cleanup"));

// Output after both tasks complete: "Cleanup"

这些高级用法能够更加灵活地处理异步操作,使代码更为清晰和可维护。


原文链接:codingdict.net