Promise对象

本文介绍了 Promise构造函数以及此类对象的方法和属性;

语法:

new Promise(executor);

executor 参数 是一个 函数,这个函数又有两个函数类型的参数 resolvereject(即 resolvereject 都是函数)。

new Promise( function(resolve, reject) {...} /* executor */  );

当执行Promise的时候 executor函数也会立即执行,在Promise构造函数返回创建的对象之前executor 就已经执行了。

看个栗子就明白了:

var promise = new Promise(function (resolve, reject) {
    console.log('the executor function is called before the Promise constructor even returns the created object');
    resolve('happy chen');
});

promise.then(function (value) {
    console.log(value);
});

console.log('promise===' + promise);
// the executor function is called before the Promise constructor even returns the created object
// promise===[object Promise]
// happy chen

resolvereject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)。

executor 内部通常会执行一些异步操作,一旦异步操作执行完毕,either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.(这句话不知道怎么翻译合适,直接看原文比较好理解)

如果在executor函数中抛出一个错误,那么该promise 状态为rejected。executor函数的返回值被忽略。

Promise 对象是一个代理对象(代理一个值),被代理的值在Promise对象创建时可能是未知的。它允许你为异步操作的成功和失败分别绑定相应的处理方法(handlers)。 这让异步方法可以像同步方法那样返回值,但并不是立即返回最终执行结果,而是一个能代表未来结果的 promise对象,注意,返回的是一个promise对象。

一个 Promise会处于以下状态之一:

  • pending:初始状态,既不是成功,也不是失败状态。
  • fulfilled:操作成功完成。
  • rejected:操作失败。

pending 状态的 Promise 对象可能会变为fulfilled 状态并传递一个值给相应的状态处理方法,也可能变为失败状态(rejected)并传递失败信息。当其中任一种情况出现时,Promise 对象的 then 方法绑定的处理方法(handlers )就会被调用(then方法包含两个参数:onfulfilled 和 onrejected,它们都是 Function 类型。当Promise状态为fulfilled时,调用 then 的 onfulfilled 方法,当Promise状态为rejected时,调用 then 的 onrejected 方法, 所以在异步操作的完成和绑定处理方法之间不存在竞争)。

因为 Promise.prototype.then 和 Promise.prototype.catch 方法返回promise 对象, 所以它们可以被链式调用。

创建Promise对象

Promise 对象是由关键字 new 及其构造函数来创建的。该构造函数会把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数(resolve 和 reject)作为其参数。当异步任务顺利完成且返回结果值时,会调用 resolve 函数;而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用reject 函数。

let myPromise = new Promise((resolve, reject) => {
    // do something asynchronous which eventually calls either:
    //
    //resolve(somevalue);//fulfilled
    //or
    //reject(failReason);//rejected
})

提供具有promise功能的函数,只需让它返回一个promise即可(To provide a function with promise functionality, simply have it return a promise:):

function AsyncFunction(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onload = () => resolve(xhr.responseText);
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send();
    });
}

举个简单的栗子:

let myPromise = new Promise((resolve, reject) => {
    // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
    // In this example, we use setTimeout(...) to simulate async code. 
    // In reality, you will probably be using something like XHR or an HTML5 API.
    setTimeout(function () {
        resolve('I did it!')// Yay!Everything went well!
    }, 250)
});

myPromise.then((successMsg) => {
    // successMessage is whatever we passed in the resolve(...) function above.
    // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
    console.log('Good News! ' + successMsg);
})

//打印:Good News! I did it!

举个高级的栗子:

var promiseCount = 0;

function testPromise() {
    let thisPromiseCount = ++promiseCount;

    console.log(thisPromiseCount + ') Started ----Sync code started');

    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
    let p1 = new Promise(
        // The executor function is called with the ability to resolve or
        // reject the promise
        (resolve, reject) => {
            console.log(thisPromiseCount + ') Promise started,the executor function is called ----Async code started');
            // This is only an example to create asynchronism
           setTimeout(
                function () {
                    // We fulfill the promise !
                    resolve(thisPromiseCount);
                    // reject('something went wrong');
                }, Math.random() * 1000 + 1000);
        }
    );

    // We define what to do when the promise is resolved with the then() call,
    // and what to do when the promise is rejected with the catch() call
    p1.then(
        // Log the fulfillment value
        function (val) {
            console.log(val + ') Promise fulfilled ----Async code terminated');
        }).catch(
            // Log the rejection reason
            (reason) => {
                console.log('Handle rejected promise (' + reason + ') here.');
            });

    console.log(thisPromiseCount + ') Promise made ----Sync code terminated');
}
testPromise()

简化下上面的例子:

let promiseCount = 0;

function testPromise() {
    let thisCount = ++promiseCount;
    console.log(`${thisCount} start Sync code start`);

    let p = new Promise((resolve, reject) => {
        console.log(`${thisCount} promise start,the executor function is called`);
        setTimeout(function () {
            resolve(thisCount)
        }, Math.random() * 1000 + 1000)
    })

    p.then((val) => {
        console.log(`${val} promise fulfilled,Async code terminated`);
    }).catch((reason) => {
        console.log(`Handle rejected promise for ${reason} `);
    })
    console.log(`${thisCount} promise made,Sync code terminated`);
}

testPromise()
// 1 start Sync code start
// 1 promise start,the executor function is called
// 1 promise made,Sync code terminated
// 1 promise fulfilled,Async code terminated

运行效果:
在这里插入图片描述
注意打印顺序,fulfilled总是后面才打印出来。

即使是多次调用testPromise()
在这里插入图片描述
fulfilled也是在最后面打印出来:

testPromise()
testPromise()
testPromise()
// 打印结果:
// 1 start Sync code start
// 1 promise start,the executor function is called
// 1 promise made,Sync code terminated
// 2 start Sync code start
// 2 promise start,the executor function is called
// 2 promise made,Sync code terminated
// 3 start Sync code start
// 3 promise start,the executor function is called
// 3 promise made,Sync code terminated
// 3 promise fulfilled,Async code terminated
// 1 promise fulfilled,Async code terminated
// 2 promise fulfilled,Async code terminated

Promise构造函数的属性

  • Promise.length:length属性,其值总为 1 (是Promise构造函数参数的数目)
  • Promise.prototype:Promise构造函数的原型(Represents the prototype for the Promise constructor)

Promise构造函数的方法(静态方法)

1,Promise.all(iterable):Promise.all方法常被用于处理多个promise对象的状态集合。(详见
2,Promise.reject(reason):返回一个状态为失败的Promise对象,并将给定的失败信息传递给对应的处理方法。(详见
3,Promise.resolve(value):返回一个状态为失败的Promise对象,并将给定的失败信息传递给对应的处理方法。(详见
3,Promise.race(iterable): 方法返回一个 promise,一旦迭代器(iterable)中的某个promise解决(fulfill)或拒绝(reject),返回的 promise就得到那个promise解决(fulfill)的返回值(value)或拒绝(reject)的原因(reason)。(详见

Promise 原型

属性:Promise.prototype.constructor

返回 所创建的实例的原型函数。默认情况下,是Promise函数。

方法:

Promise.prototype.then()then() 方法返回一个 Promise。它有两个参数:Promise 成功和失败时的回调函数。(详见
Promise.prototype.catch():(详见
Promise.prototype.finally(onFinally)finally() 方法返回一个Promise。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。(详见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值