Promise 其实很简单

Promise 是什么?

Promise 的定义

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object you attach callbacks to, instead of passing callbacks into a function.

Promise 是一个表示异步操作最终完成或失败的对象,可以直接向其添加回调函数,而不必将回调函数传进方法。

Promise 有三种状态:Pending、Resolved、Rejected。初始是 Pendding 状态,表示异步操作正在执行。调用 resolve 方法可以让其状态从 Pendding 变为 Resolved,此时 then 方法中的第一个回调函数被触发;调用 reject 方法可以让其状态从 Pending 变为 Rejected 状态,此时 then 方法中的第二个回调函数被触发。

Promise 的简单使用

使用方法

const promise = new Promise(function(resolve, reject) {
    // 异步操作,返回之后
        // 判断异步操作的结果
        if (/* 成功 */) {
            resolve("Resolved");
        } else {            reject("Rejected");
        }
})

promise.then(onResolved, onRejected)
             .catch(e => handleError(e));

// 异步操作成功的回调
function onResolved(result) {
    console.log(result);
}

// 异步操作失败的回调
function onRejected(reason) {
    console.log(reason);
}

// 异常处理函数
function handleError(e) {
    throw new Error("Error");
}
复制代码

Promise 封装 XMLHttpRequest

看下面一个封装 XMLHttpRequest 对象的例子:

const getJSON = function (url) {

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

        const handler = function () {

            if (this.readyState !== 4) {

                return;

            }

            if (this.status === 200) {

                resolve(this.response);

            } else {

                reject(new Errer(this.statusText));

            }

        };

        const client = new XMLHttpRequest();

        client.open("GET", url);

        client.onreadystatechange = handler;

        client.responseType = "json";

        client.setRequestHeader("Accept", "application/json");

        client.send();

    });

};

getJSON("posts.json").then(function(json){

    console.log('Contents: ' + json);

}, function(error){

    console.log('出错了', error);

});
复制代码

链式调用

function taskA() {
    console.log("Task A");
}
function taskB() {
    console.log("Task B");
}
function onRejected(error) {
    console.log("Catch Error: A or B", error);
}

var promise = Promise.resolve();
promise
    .then(taskA)
    .then(taskB)
    .catch(onRejected) // 捕获前面then方法中的异常

复制代码

Promise 的静态方法 all

All 方法用于多个独立的异步操作,对多个异步操作的结果做汇总。

const p1 = new Promise((resolve, reject) => {
    resolve(1);
})

const p2 = new Promise((resolve, reject) => {
    resolve(2);
});

const p3 = new Promise((resolve, reject) => {
    resolve(3);
});

Promise.all([p1, p2, p3]).then(data => { 
    console.log(data); //  [1, 2, 3] 结果顺序和promise实例数组顺序是一致的
}, err => {
    console.log(err);
});

复制代码

Promise 的静态方法 race

Promise.race 只要有一个 Promise 对象进入 Resolved 或 Rejected 状态,Promise 就进入相应的状态。

function timerPromisefy(delay) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(delay);
        }, delay);
    });
}

Promise.race([
    timerPromisefy(10),
    timerPromisefy(20),
    timerPromisefy(30)
]).then(function (values) {
    console.log(values); // 10
});
复制代码

说白了,Promise 就是一个包含了异步操作结果的对象,它可以根据结果来决定该执行哪个回调函数。

结论

本质的本质,Promise 就是一个组织异步操作的工具。以前用回调函数处理异步的时候是这样流程:
(1)执行异步操作 ——》(2)异步返回 ——》(3)回调函数
现在用 Promise 的流程是这样的:
(1)执行异步操作 ——》(2)异步返回 ——》(3)Promise 的对象方法和静态方法 ——》(4)回调函数
在第三步中我们有了更多的选择,可以对异步操作进行进一步的管理和组织,因此使得异步曹操逻辑更加易于维护。

参考文章:
Promise 原理讲解
JavaScript: Promises explained with simple real life analogies

猜你喜欢

转载自juejin.im/post/5c98d208e51d4528b443f35d