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}复制代码
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复制代码
Object.getOwnPropertyNames(p); // []
Object.getOwnPropertyNames(o); // ["a", "b"]
复制代码
Object.keys(p); // []
Object.keys(o); // ["a", "b"]
复制代码
Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最先提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise
对象。
json
所谓Promise
,简单说就是一个容器,里面保存着某个将来才会结束的事件(一般是一个异步操做)的结果。从语法上说,Promise 是一个对象,从它能够获取异步操做的消息。Promise 提供统一的 API,各类异步操做均可以用一样的方法进行处理。
axios
@Promise容器包装的异步函数有三个状态:segmentfault
@一旦状态改变,就不会再变, 好比,用Promise包装的一个ajax请求数组
简单的说就是 解决回调地域的写法,用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
\\......
}
}
})复制代码
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);
})复制代码
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);
});复制代码
ES6 规定,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
构造函数接受一个函数做为参数,该函数的两个参数分别是resolve
和reject
。它们是两个函数,由 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
对象传出的值做为参数。
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
最后输出。
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()) ), 这种场景不多,先无论。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
复制代码
上面代码中,调用resolve(1)
之后,后面的console.log(2)
仍是会执行,而且会首先打印出来。这是由于当即 resolved 的 Promise 是在本轮事件循环的末尾执行,老是晚于本轮循环的同步任务。
通常来讲,调用resolve
或reject
之后,Promise 的使命就完成了,后继操做应该放到then
方法里面,而不该该直接写在resolve
或reject
的后面。因此,最好在它们前面加上return
语句,这样就不会有意外。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的语句不会执行
console.log(2);
})复制代码
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
方法是.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 会吃掉错误”。
finally
方法用于指定无论 Promise 对象最后状态如何,都会执行的操做。该方法是 ES2018 引入标准的。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});复制代码
上面代码中,无论promise
最后的状态,在执行完then
或catch
指定的回调函数之后,都会执行finally
方法指定的回调函数。
finally
本质上是then
方法的特例。
promise
.finally(() => {
// 语句
});
// 等同于
promise
.then(
result => {
// 语句
return result;
},
error => {
// 语句
throw error;
}
);复制代码
上面代码中,若是不使用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 实例,包装成一个新的 Promise 实例。
const p = Promise.all([p1, p2, p3]);
复制代码
上面代码中,Promise.all()
方法接受一个数组做为参数,p1
、p2
、p3
都是 Promise 实例,若是不是,就会先调用下面讲到的Promise.resolve
方法,将参数转为 Promise 实例,再进一步处理。另外,Promise.all()
方法的参数能够不是数组,但必须具备 Iterator 接口,且返回的每一个成员都是 Promise 实例。
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 对象,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(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;
});
};复制代码
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
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复制代码
resolve
函数和reject
函数时带有参数,那么它们的参数会被传递给then中的回调函数。var XHR = new XMLHttpRequest()
XHR.__proto__.__proto__.__proto__.__proto__.__proto__ === null ;// true
复制代码
感谢阮一峰老师的付出,本文主要内容来源于阮一峰老师博客,特此说明