Promise构造函数那点事

new Promise的原型链 Promise的实例对象Promise 的含义promise的简单使用Promise.prototype.then()Promise.prototype.catch()Promise.prototype.finally()Promise.all()Promise.resolve()Promise.reject()应用总结

new Promise的原型链

var p = new Promise((resolve,reject)=>{resolve(1)})
.then((res)=>{console.log(res)}); // 1复制代码

p是Promise的实例,那么p的原型链咱们看一下,javascript

p.__proto__.__proto__.__proto__===null复制代码

p实例是个啥?java

Object.prototype.toString.call(p); // "[object Promise]"复制代码

p是一个promise 实例对象,为普通的对象有什么区别?ios

咱们遍历一下这个p上的key,value都有啥?ajax

如下咱们与普通对象o作对比编程

var p = new Promise((resolve,reject)=>{resolve(1)})
.then((res)=>{console.log(res)}); // 1 var o = {a:1,b:2}复制代码

1. 使用for  in来遍历一个对象

for(var key in p){
   console.log(key,p[key])
}
//undefined

for(var key in o){
   console.log(key,o[key])
}
// a 1
// b 2复制代码

2. 使用Object.getOwnPropertyNames()来获取key名数组

Object.getOwnPropertyNames(p); // []
Object.getOwnPropertyNames(o); // ["a", "b"]
复制代码

3. 经过Object.keys(),来看有什么key值

Object.keys(p); // []
Object.keys(o); // ["a", "b"]
复制代码


p这个Promise的实例对象上为啥什么都没有???先保留此问题


@ 看一下Promise的原型对象上有什么?


为何只有catch   constructor   finally   then,那么   all  race  try等Promise上的方法是从何而来? 先保留此问题


Promise(“承诺”) 的含义与特色与解决了什么问题

Promise的含义

Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最先提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。
json

所谓Promise,简单说就是一个容器,里面保存着某个将来才会结束的事件(一般是一个异步操做)的结果。从语法上说,Promise 是一个对象,从它能够获取异步操做的消息。Promise 提供统一的 API,各类异步操做均可以用一样的方法进行处理。
axios

Promise的特色

@Promise容器包装的异步函数有三个状态:segmentfault

  1.  pendding
  2. resolve
  3. reject

@一旦状态改变,就不会再变, 好比,用Promise包装的一个ajax请求数组

  1. 要么成功,成功后不可能在失败
  2. 要么失败,失败后也不可能在成功

解决了什么问题

简单的说就是 解决回调地域的写法,用then链式调用来取代层层嵌套的回调的写法。
promise

好比,有三个异步函数 a,b,c,b依赖a异步函数执行后的数据,c依赖异步函数b的执行结果

那么,咱们可能就只能用嵌套的写法去写, 以下代码:

回调地狱伪代码:

async a(()=>{    
    var dataA = "异步函数b依赖的数据"

    async b((dataA)=>{  

      var dataB = "异步函数c依赖的数据"
        async c((dataB)=>{  
            return dataA + dataB + dataC   
            \\......      
        }    
    }
})复制代码

用promise怎么写呢?

function timeout(ms,data) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms, data);
  });
}

timeout(1000,'dataA')
.then((value) => {
  console.log(value);
  return timeout(3000,value+" "+'dataB')
})
.then((value) =>{
	console.log(value);
    return timeout(3000,value+" "+'dataC')
}).then((value)=>{
    console.log(value);
})复制代码

@另一个Promise读取文件的例子

function getFileByPath(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf-8', (err, data) => {
            if (err) {
                return reject(err);
            }
            resolve(data);
        });
    });
}
getFileByPath(path.join(__dirname, './1.txt'))
    .then(function(data) {
        console.log(data);
        return getFileByPath(path.join(__dirname, './2.txt'));
    }).then(function(data) {
        console.log(data);
        return getFileByPath(path.join(__dirname, './3.txt'));
    }).then(function(data) {
        console.log(data);
    }).catch(function(err) {
        console.log(err.message);
    });复制代码


promise的简单使用

ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。

下面代码创造了一个Promise实例。

const p = new Promise((resolve,reject)=>{
    //... do something
    if(/*成功*/){
        resolve(data)
    }else{
        reject(err)
    }
}).then((data)=>{
    console.log(data);//拿到resolve参数中的data
}).catch((err)=>{
    console.log(err)
    throw new Error('err')
})复制代码

Promise构造函数接受一个函数做为参数,该函数的两个参数分别是resolvereject。它们是两个函数,由 JavaScript 引擎提供,不用本身部署。

resolve函数的做用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操做成功时调用,并将异步操做的结果,做为参数传递出去reject函数的做用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操做失败时调用,并将异步操做报出的错误,做为参数传递出去

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

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});
复制代码

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

@Promise 新建后就会当即执行。

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

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

console.log('Hi!');

// Promise
// Hi!
// resolved
复制代码

上面代码中,Promise 新建后当即执行,因此首先输出的是Promise。而后,then方法指定的回调函数,将在当前脚本全部同步任务执行完才会执行,因此resolved最后输出。

下面是一个用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);
});
复制代码

上面代码中,getJSON是对 XMLHttpRequest 对象的封装,用于发出一个针对 JSON 数据的 HTTP 请求,而且返回一个Promise对象。须要注意的是,在getJSON内部,resolve函数和reject函数调用时,都带有参数。

若是调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给回调函数。reject函数的参数一般是Error对象的实例,表示抛出的错误;resolve函数的参数除了正常的值之外,还多是另外一个 Promise 实例(  好比 resolve(new 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 是在本轮事件循环的末尾执行,老是晚于本轮循环的同步任务。

通常来讲,调用resolvereject之后,Promise 的使命就完成了,后继操做应该放到then方法里面,而不该该直接写在resolvereject的后面。因此,最好在它们前面加上return语句,这样就不会有意外。

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

Promise.prototype.then()

Promise 实例具备then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的做用是为 Promise 实例添加状态改变时的回调函数。前面说过,then方法的第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。所以能够采用链式写法,即then方法后面再调用另外一个then方法。

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});复制代码

Promise.prototype.catch()

Promise.prototype.catch方法是.then(null, rejection).then(undefined, 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));复制代码

promise.catch模拟的是catch代码块。

catch方法返回的仍是一个 Promise 对象,所以后面还能够接着调用then方法。

下面是一个例子。

const promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error);
});
// Error: test
复制代码

上面代码中,promise抛出一个错误,就被catch方法指定的回调函数捕获。注意,上面的写法与下面两种写法是等价的。

// 写法一
const promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) {
    reject(e);
  }
});
promise.catch(function(error) {
  console.log(error);
});

// 写法二
const promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});
复制代码

比较上面两种写法,能够发现reject方法的做用,等同于抛出错误。

通常来讲,不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),老是使用catch方法。

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });复制代码

上面代码中,第二种写法要好于第一种写法,理由是第二种写法能够捕获前面then方法执行中的错误,也更接近同步的写法(try/catch)。所以,建议老是使用catch方法,而不使用then方法的第二个参数。

const someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    // 下面一行会报错,由于x没有声明
    resolve(x + 2);
  });
};

someAsyncThing().then(function() {
  console.log('everything is great');
});

setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123复制代码

上面代码中,someAsyncThing函数产生的 Promise 对象,内部有语法错误。浏览器运行到这一行,会打印出错误提示ReferenceError: x is not defined,可是不会退出进程、终止脚本执行,2 秒以后仍是会输出123。这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,通俗的说法就是“Promise 会吃掉错误”。

Promise.prototype.finally()

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

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});复制代码

上面代码中,无论promise最后的状态,在执行完thencatch指定的回调函数之后,都会执行finally方法指定的回调函数。

finally本质上是then方法的特例。

promise
.finally(() => {
  // 语句
});

// 等同于
promise
.then(
  result => {
    // 语句
    return result;
  },
  error => {
    // 语句
    throw error;
  }
);复制代码

上面代码中,若是不使用finally方法,一样的语句须要为成功和失败两种状况各写一次。有了finally方法,则只须要写一次。

finally的实现也很简单。

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};
复制代码

上面代码中,无论前面的 Promise 是fulfilled仍是rejected,都会执行回调函数callback

从上面的实现还能够看到,finally方法老是会返回原来的值。

// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})

// resolve 的值是 2
Promise.resolve(2).finally(() => {})

// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})

// reject 的值是 3
Promise.reject(3).finally(() => {})复制代码

Promise.all()

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

const p = Promise.all([p1, p2, p3]);
复制代码

上面代码中,Promise.all()方法接受一个数组做为参数,p1p2p3都是 Promise 实例,若是不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。另外,Promise.all()方法的参数能够不是数组,但必须具备 Iterator 接口,且返回的每一个成员都是 Promise 实例。

p的状态由p1p2p3决定,分红两种状况。

(1)只有p1p2p3的状态都变成fulfilledp的状态才会变成fulfilled,此时p1p2p3的返回值组成一个数组,传递给p的回调函数。

(2)只要p1p2p3之中有一个被rejectedp的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

Promise.resolve()

有时须要将现有对象转为 Promise 对象,Promise.resolve()方法就起到这个做用。

const jsPromise = Promise.resolve($.ajax('/whatever.json'));
复制代码

上面代码将 jQuery 生成的deferred对象,转为一个新的 Promise 对象。

Promise.resolve()等价于下面的写法。

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
复制代码

Promise.resolve方法的参数分红四种状况。

(1)参数是一个 Promise 实例

若是参数是 Promise 实例,那么Promise.resolve将不作任何修改、原封不动地返回这个实例。

(2)参数是一个thenable对象

thenable对象指的是具备then方法的对象,好比下面这个对象。

let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
};
复制代码

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
});
复制代码

上面代码中,thenable对象的then方法执行后,对象p1的状态就变为resolved,从而当即执行最后那个then方法指定的回调函数,输出 42。

(3)参数不是具备then方法的对象,或根本就不是对象

若是参数是一个原始值,或者是一个不具备then方法的对象,则Promise.resolve方法返回一个新的 Promise 对象,状态为resolved

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

p.then(function (s){
  console.log(s)
});
// Hello复制代码


上面代码生成一个新的 Promise 对象的实例p。因为字符串Hello不属于异步操做(判断方法是字符串对象不具备 then 方法),返回 Promise 实例的状态从一辈子成就是resolved,因此回调函数会当即执行。Promise.resolve方法的参数,会同时传给回调函数。

(4)不带有任何参数

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

因此,若是但愿获得一个 Promise 对象,比较方便的方法就是直接调用Promise.resolve()方法。

const p = Promise.resolve();

p.then(function () {
  // ...
});
复制代码

上面代码的变量p就是一个 Promise 对象。

须要注意的是,当即resolve()的 Promise 对象,是在本轮“事件循环”(event loop)的结束时执行,而不是在下一轮“事件循环”的开始时。

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');

// one
// two
// three
复制代码

上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是当即执行,所以最早输出。

console.log(1)
Promise.resolve(console.log(2));
console.log(3)
// 1
// 2
// 3复制代码

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)
});
// 出错了
复制代码

上面代码生成一个 Promise 对象的实例p,状态为rejected,回调函数会当即执行。

注意,Promise.reject()方法的参数,会原封不动地做为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致。

const thenable = {
  then(resolve, reject) {
    reject('出错了');
  }
};

Promise.reject(thenable)
.catch(e => {
  console.log(e === thenable)
})
// true
复制代码

上面代码中,Promise.reject方法的参数是一个thenable对象,执行之后,后面catch方法的参数不是reject抛出的“出错了”这个字符串,而是thenable对象。


应用

加载图片

咱们能够将图片的加载写成一个Promise,一旦加载完成,Promise的状态就发生变化。

const preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
};复制代码

Promise容器包装setTimeout,去控制setTimeout的执行顺序

Promise容器包装ajax,去控制ajax的执行顺序

Promise容器包装axios,去控制axios的执行顺序<--axios到底有没有必要在包一层promise

axios返回的就是一个promise对象 为何有不少人仍是会promise再封装一次呢?


function myGet(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, params).then(function (response) {
      resolve(response.data)
    })
    .catch(function (err) {
      reject(err)
    })
  })
}
 
myGet(url,params).then(function(data){console.log(data)}).catch(function(){})
复制代码

参考:segmentfault.com/q/101000001…

结论:axios到底没有必要在包一层promise


Promise中的数据传递

var fn = function(num) {
    return new Promise(function(resolve, reject) {
        if (typeof num == 'number') {
            resolve(num);
        } else {
            reject('TypeError');
        }
    })
}

fn(2).then(function(num) {
    console.log('first: ' + num);
    return num + 1;
})
.then(function(num) {
    console.log('second: ' + num);
    return num + 1;
})
.then(function(num) {
    console.log('third: ' + num);
    return num + 1;
});

// 输出结果
first: 2
second: 3
third: 4复制代码


总结

  • Promise是一个异步函数的 容器
  • 若是调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给then中的回调函数。
  •  最好在resolve()前面加上 return 语句,不然,resolve后面的代码仍是会执行。
  • then(cb1,cb2), cb1等待上方的异步函数的状态变为resolved才会执行,cb2会等上方的异步函数变为reject时会执行。
  • Promise 会吃掉错误
  • xhr的原型链 

var XHR = new XMLHttpRequest()
XHR.__proto__.__proto__.__proto__.__proto__.__proto__ === null ;// true
复制代码


感谢阮一峰老师的付出,本文主要内容来源于阮一峰老师博客,特此说明

相关文章
相关标签/搜索