一、Promise介绍和优缺点
Promise是异步编程的一种解决方案。
Promise对象有以下两个特点:
1、对象的状态不受外界影响。Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。
2、一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。
Promise缺点:
1、无法取消Promise,一旦新建它就会立即执行,无法中途取消。
2、如果不设置回调函数,Promise内部抛出的错误,不会反应到外部。
3、当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。
二、基本用法:
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
Promise 新建后就会立即执行。
resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”,在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”,在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then方法可以接受两个回调函数作为参数:第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。第二个函数是可选的,不一定要提供。
三、Promise实例的then方法
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此then方法可以采用链式写法,即then方法后面再调用另一个then方法。
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
四、Promise实例的catch方法
Promise.prototype.catch方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。
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方法,这样可以处理 Promise 内部发生的错误。catch方法返回的还是一个 Promise 对象,因此后面还可以接着调用then方法。
Promise.resolve()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
五、Promise实例的finally方法
finally方法:用于指定不管 Promise 对象最后状态如何,都会执行的操作。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
六、Promise.resolve()
Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
七、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)// 打印'出错了'
});
八、for...of循环
for...of循环可以代替数组实例的forEach方法。JavaScript 原有的for...in
循环,只能获得对象的键名,不能直接获取键值。
const arr = ['red', 'green', 'blue'];
for(let v of arr) {
console.log(v); // red green blue
}
//代替下面的forEach
arr.forEach(function (element, index) {
console.log(element); // red green blue
console.log(index); // 0 1 2
});
//for...in循环
for (let a in arr) {
console.log(a); // 0 1 2
}
以数组为例,总结一下与其他遍历语法的比较:
1、原始for循环:写法比较麻烦。
for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}
2、forEach方法:无法中途跳出forEach循环,break命令或return命令都不能奏效。
myArray.forEach(function (value) {
console.log(value);
});
3、for...in循环:可以遍历数组的键名,主要是为遍历对象而设计的,不适用于遍历数组。
for (var index in myArray) {
console.log(myArray[index]);
}
所以for...of循环有着显著的优点:A、简洁;B、可以与break、continue和return配合使用;