JS Promise对象的基本使用

JS8个月前更新 铁老班
0

Promise 对象

三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)

Promise对象的状态改变,只有两种可能:
从pending变为fulfilled
从pending变为rejected。

缺点:
1、无法取消Promise,一旦新建它就会立即执行,无法中途取消
2、如果不设置回调函数,Promise内部抛出的错误,不会反应到外部
3、当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。

const promise = new Promise(function(resolve, reject) {
    // ... some code

    if (/* 异步操作成功 */){
        resolve(value);
    } else {
        reject(error);
    }
});

Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。

promise.then(function(value) {
    // success
}, function(error) {
    // failure
});

then方法接受两个回调函数作为参数
第一个回调函数是Promise对象的状态变为resolved时调用,
第二个回调函数是Promise对象的状态变为rejected时调用。
其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。

let promise = new Promise(function(resolve, reject) {
    console.log('Promise');
    resolve();
});

promise.then(function() {
    console.log('resolved.');
});

console.log('Hi!');
异步加载图片的例子
function loadImageAsync(url) {
      return new Promise(function(resolve, reject) {
        const image = new Image();

        image.onload = function() {
          resolve(image);
        };

        image.onerror = function() {
          reject(new Error('Could not load image at ' + url));
        };

        image.src = url;
      });
    }
用Promise对象实现的 Ajax 操作的例子
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 Error(this.statusText));
            }
        };

        const client = new XMLHttpRequest();
        client.open("GET", url);
        client.onreadystatechange = handler;
        client.responseType = "json";
        client.setRequestHeader("Accept", "application/json");
        client.send();
    });

    return promise;
};

getJSON("/posts.json").then(function(json) {
    console.log('Contents: ' + json);
}, function(error) {
    console.error('出错了', error);
});
另一个 Promise 实例,
const p1 = new Promise(function (resolve, reject) {
    // ...
});

const p2 = new Promise(function (resolve, reject) {
    // ...
    resolve(p1);
})

这时p1的状态就会传递给p2,也就是说,p1的状态决定了p2的状态。
如果p1的状态是pending,那么p2的回调函数就会等待p1的状态改变;
如果p1的状态已经是resolved或者rejected,那么p2的回调函数将会立刻执行。

另一个 Promise 实例,
const p1 = new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('fail')), 3000)
})

const p2 = new Promise(function (resolve, reject) {
    setTimeout(() => resolve(p1), 1000)
})

p2.then(result => console.log(result))
    .catch(error => console.log(error))
// Error: fail

p1是一个 Promise,3 秒之后变为rejected。
p2的状态在 1 秒之后改变,resolve方法返回的是p1。
由于p2返回的是另一个 Promise,导致p2自己的状态无效了,由p1的状态决定p2的状态。
后面的then语句都变成针对后者(p1)。
又过了 2 秒,p1变为rejected,导致触发catch方法指定的回调函数。

另一个 Promise 实例,

调用resolve或reject并不会终结 Promise 的参数函数的执行。

new Promise((resolve, reject) => {
    resolve(1);
    console.log(2);
}).then(r => {
    console.log(r);
});
// 2
// 1

调用resolve(1)以后,后面的console.log(2)还是会执行,并且会首先打印出来。
这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务。

new Promise((resolve, reject) => {
    return resolve(1);
    // 后面的语句不会执行
    console.log(2);
})

一般来说,调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,
而不应该直接写在resolve或reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。

Promise.prototype.then()

第一个参数是resolved状态的回调函数,
第二个参数(可选)是rejected状态的回调函数。

getJSON("/posts.json").then(function(json) {
    return json.post;
}).then(function(post) {
    // ...
});

上面的代码使用then方法,依次指定了两个回调函数。
第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),
这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。

getJSON("/post/1.json").then(function(post) {
    return getJSON(post.commentURL);
}).then(function funcA(comments) {
    console.log("resolved: ", comments);
}, function funcB(err){
    console.log("rejected: ", err);
});

第一个then方法指定的回调函数,返回的是另一个Promise对象。
这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。
如果变为resolved,就调用funcA,如果状态变为rejected,就调用funcB。

Promise.prototype.catch()

Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。

getJSON('/posts.json').then(function(posts) {
    // ...
}).catch(function(error) {
    // 处理 getJSON 和 前一个回调函数运行时发生的错误
    console.log('发生错误!', error);
});

上面代码中,getJSON方法返回一个 Promise 对象,
如果该对象状态变为resolved,则会调用then方法指定的回调函数;
如果异步操作抛出错误,状态就会变为rejected,就会调用catch方法指定的回调函数,处理这个错误。

另外,then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获。

p.then((val) => console.log('fulfilled:', val))
    .catch((err) => console.log('rejected', err));
// 等同于
p.then((val) => console.log('fulfilled:', val))
    .then(null, (err) => console.log("rejected:", err));
下面是一个例子。
const promise = new Promise(function(resolve, reject) {
    throw new Error('test');
});
promise.catch(function(error) {
    console.log(error);
});
// Error: test

someAsyncThing().then(function() {
    return someOtherAsyncThing();
}).catch(function(error) {
    console.log('oh no', error);
    // 下面一行会报错,因为y没有声明
    y + 2;
}).catch(function(error) {
    console.log('carry on', error);
});

第二个catch方法用来捕获前一个catch方法抛出的错误

Promise.prototype.finally()

finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。

promise
    .then(result => {···})
    .catch(error => {···})
    .finally(() => {···});

Promise.all()

romise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。

const p = Promise.all([p1, p2, p3]);

p的状态由p1、p2、p3决定,分成两种情况。
(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

Promise.race()

Promise.race方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。

const p = Promise.race([p1, p2, p3]);

只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。
那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

const p = Promise.race([
    fetch('/resource-that-may-take-a-while'),
    new Promise(function (resolve, reject) {
        setTimeout(() => reject(new Error('request timeout')), 5000)
    })
]);

p.then(console.log)
    .catch(console.error);

如果 5 秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数。

Promise.resolve()

将 jQuery 生成的deferred对象,转为一个新的 Promise 对象

const jsPromise = Promise.resolve($.ajax('/whatever.json'));

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
Promise.resolve方法的参数分成四种情况。

(1)参数是一个 Promise 实例
如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。

(2)参数是一个thenable对象
thenable对象指的是具有then方法的对象。
Promise.resolve方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then方法

let thenable = {
    then: function(resolve, reject) {
        resolve(42);
    }
};

let p1 = Promise.resolve(thenable);
p1.then(function(value) {
    console.log(value);  // 42
});

(3)参数不是具有then方法的对象,或根本就不是对象
如果参数是一个原始值,或者是一个不具有then方法的对象,则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved。

const p = Promise.resolve('Hello');

p.then(function (s){
    console.log(s)
});
// Hello

(4)不带有任何参数
Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的 Promise 对象。

Promise.reject()

Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected

const p = Promise.reject('出错了');
// 等同于
const p = new Promise((resolve, reject) => reject('出错了'))

p.then(null, function (s) {
    console.log(s)  // 出错了
});
廖大神教程地址https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544
© 版权声明

相关文章