【一起来烧脑】读懂Promise知识体系
知识体系
Promise基础语法,如何处理错误,简单介绍异步函数
内容
错误处理的两种方式:
reject('错误信息').then(null, message => {})
throw new Error('错误信息').catch(message => {})
推荐第二种
4个案例promise
// 1
doSomething().then(function () {
return doSomethingElse();
});
// 2
doSomething().then(function () {
doSomethingElse();
});
// 3
doSomething().then(doSomethingElse());
// 4
doSomething().then(doSomethingElse);
.then()
状态响应函数可以返回新的Promise,或其它值
如果返回新的Promise,那么下一级.then()
会在新Promise状态改变之后执行
如果返回其它任何值,则会立刻执行下一级.then()
.then()
接受两个函数作为参数:
fulfilled
和rejected
.then()
返回一个新的Promise实例,所以它可以链式调用
当前面的Promise状态改变时,.then()
根据其最终状态,选择特定的状态响应函数执行
可以有多个then,成为队列,每个then都会返回一个新的promise实例
[外链图片转存失败(img-jXpVtXtc-1563275786816)(https://upload-images.jianshu.io/upload_images/11158618-ba6cb93c0c741859.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
promise状态
Promise状态发生改变,会触发.then()
里的响应函数处理后续步骤。
Promise状态一经改变,不会再变。
promise 结构!!
new Promise(
// 执行器
function (resolve, reject) {
// 一段耗时很长的异步操作
resolve(); // 数据处理完成
reject(); // 数据处理出错
}
).then(function A() {
// 成功,下一步
}, function B() {
// 失败
});
Promise.race()
常见用法:
把异步操作和定时器放在一起
如果定时器先触发,就认为超时,告知用户
thenable就是有一个then()函数的对象
.then( value => {
console.log(value, 'World');
return Promise.resolve(new Promise( resolve => {
setTimeout(() => {
resolve('Good');
}, 2000);
}));
})
.then( value => {
console.log(value, 'evening');
return Promise.resolve({
then() {
console.log('everone');
}
})
});
Promise.all 与map
把所有文件读出之后再处理,所以用到了promise.all()
const FileSystem = require('./FileSystem');
function findLargest(dir){
return FildSystem.readDir(dir, 'utf-8')
.then( files => {
return Promise.all( files.map( file=> {
return new Promise(resolve => {
fs.stat(path.join(dir, file), (err, stat) => {
if(err) throw err;
if(stat.isDirectory()) {
return resolve({
size: 0
});
}
stat.file = file;
resolve(stat);
});
});
}));
})
Promise 释义
Promise对象用于异步计算
一个Promise表示一个现在,将来或永久不可能可用的值
主要用于异步计算
可以将异步操作队列化,按住期望的顺序执行,返回符合预期的结果
可以在对象之间传递和操作Promise,帮助我们处理队列
异步产生的原因
异步操作的常用语法:
document.getElementById('start').addEventListener('click', start, false);
function start() {
// 响应事件
}
// jquery
$('#start').on('click', start);
回调:
// 比较常见的有 ajax
$.ajax('http://baidu.com', {
success: function (res) {
// 这里就是回调函数了
}
});
// 或者在页面加载完毕后回调
$(function () {
// 这里也是回调函数
});
异步操作以事件为主
回调主要出现在Ajax和File API
这个时候问题尚不算严重
异步回调的问题
遍历目录,找到最大的文件
const fs = require('fs');
const path = require('path');
function findLargest(dir, callback) {
fs.readdir(dir, function (err, files) {
if (err) return callback(err);
let count = files.length;
let errored = false;
let stats = [];
files.forEach( file => {
fs.stat(path.join(dir, file), (err, stat) => {
if(errored) return;
if(err) {
errored = true;
return callback(err);
}
stats.push(stat);
Promise 简介
new Promise(
// 执行器
function (resolve, reject) {
// 一段耗时很长的异步操作
resolve(); // 数据处理完成
reject(); // 数据处理出错
}
)
.then(function A() {
// 成功,下一步
},function B() {
// 失败,做相应处理
});
Promise是一个代理对象,它和原先要进行的操作并无关系。
它通过引入一个回调。
Promise有3个状态
pending [待定] 初始状态
fulfilled [实现] 操作成功
rejected [被否决] 操作失败
promise状态发生改变,就会触发.then()
里的响应函数出来了后续步骤。
Promise状态一经改变,不会再变。
[外链图片转存失败(img-gA23f1q6-1563275786818)(https://upload-images.jianshu.io/upload_images/11158618-10641ebb84f7caa1.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
最简单的实例
定时器
new Promise( resolve => {
setTimeout( () => {
resolve('hello');
}, 2000);
})
.then( value => {
console.log( value + 'world');
});
两步执行的范例
new Promise( resolve => {
setTimeout( () => {
resolve('hello');
}, 2000);
})
.then( value => {
console.log(value);
return new Promise( resolve => {
setTimeout( () => {
resolve('world')
}, 2000);
});
})
.then(value => {
console.log(value + 'world');
});
对已完成的 Promise 执行 then
let promise = new Promise(resolve => {
setTimeout(() => {
console.log('the promise fulfilled');
resolve('hello,world');
}, 1000);
});
setTimeout( () => {
promise.then( value => {
console.log(value);
});
}, 2000);
then 里不返回 Promise
[外链图片转存失败(img-pb1Hlk9O-1563275786820)(https://upload-images.jianshu.io/upload_images/11158618-a10353f9e0f93eb3.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
then 的嵌套
[外链图片转存失败(img-ea42h6rY-1563275786825)(https://upload-images.jianshu.io/upload_images/11158618-588081b6b6e3b971.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
.then
的链式调用
[外链图片转存失败(img-VtGxiKXk-1563275786830)(https://upload-images.jianshu.io/upload_images/11158618-e92fb29df8b04954.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
console.log('start');
new Promise( resolve => {
console.log('Step 1');
setTimeout(() => {
resolve(100);
}, 1000);
})
.then( value => {
return new Promise(resolve => {
console.log('Step 1-1');
setTimeout(() => {
resolve(110);
},1000);
})
.then( value=> {
console.log('Step 1-2');
return value;
})
.then( value=> {
console.log('Step 1-3');
return value;
});
})
.then(value=> {
console.log(value);
console.log('Step 2');
});
Promise的四种情况:
doSomething()
.then(function(){
return doSomethingElse();
})
.then(finalHandler);
第一步执行,doSomething,第二步执行,doSomethingElse(undefined),第三步执行,finalHander(resultOfDoSomethingElse)
doSomething()
.then(function () {
doSomethingElse();
})
.then(finalHander);
第一步执行doSomething,第二步执行doSomethingElse(undefined),findHandler(undefined)
doSomething()
.then(doSomethingElse())
.then(finalHandler);
第一步,doSomething,doSomethingElse(undefined),第二步,finalHandler(resultOfDoSomething)
doSomething()
.then(doSomethingElse)
.then(finalHandler);
第一步doSomething,第二步doSomethingElse(resultOfDoSomething),第三步,finalHandler(resultOfDoSomethingElse)
这四项承诺有什么区别?
doSomething().then(function () {
return doSomethingElse();
});
doSomething().then(function () {
doSomethingElse();
});
doSomething().then(doSomethingElse());
doSomething().then(doSomethingElse);
错误处理
Promise会自动捕获内部异常,并交给rejected响应函数处理。
[外链图片转存失败(img-2Le2Nzt1-1563275786832)(https://upload-images.jianshu.io/upload_images/11158618-bd6dff5eebfe6a77.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-pangcVZg-1563275786833)(https://upload-images.jianshu.io/upload_images/11158618-0021384fa4d70345.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
错误和then连用
.catch + .then()
[外链图片转存失败(img-rvSdiq7W-1563275786838)(https://upload-images.jianshu.io/upload_images/11158618-1edf0bfcd0107e78.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-MpdUSfFV-1563275786840)(https://upload-images.jianshu.io/upload_images/11158618-fa8d43f841c51a52.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-L54XZ3uj-1563275786841)(https://upload-images.jianshu.io/upload_images/11158618-2e2a6b113517180d.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
Promise.all
[外链图片转存失败(img-jx0vSCMh-1563275786844)(https://upload-images.jianshu.io/upload_images/11158618-0114d601fb831a9a.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-n7lgskt8-1563275786847)(https://upload-images.jianshu.io/upload_images/11158618-08e50150a2c6e4b0.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-ttBgxamO-1563275786849)(https://upload-images.jianshu.io/upload_images/11158618-c9f412f63d3d4713.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-WKcZVtZU-1563275786850)(https://upload-images.jianshu.io/upload_images/11158618-16ccd20121a0d98a.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
与 .map 连用
[外链图片转存失败(img-wrW94rpj-1563275786851)(https://upload-images.jianshu.io/upload_images/11158618-d519d4839f785ac4.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
实现队列
[外链图片转存失败(img-L3iLa9zV-1563275786851)(https://upload-images.jianshu.io/upload_images/11158618-506f93918620bbfd.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-PB1b4bEI-1563275786854)(https://upload-images.jianshu.io/upload_images/11158618-371080deebd867fb.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-N2aSBf78-1563275786855)(https://upload-images.jianshu.io/upload_images/11158618-e655fb40dbc0d9ae.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-9ETjmwV6-1563275786856)(https://upload-images.jianshu.io/upload_images/11158618-1acd9aa01d2f44a6.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-cNWApSMG-1563275786858)(https://upload-images.jianshu.io/upload_images/11158618-5dbd4a81a3cc37d7.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
[外链图片转存失败(img-ORm5ywmt-1563275786859)(https://upload-images.jianshu.io/upload_images/11158618-b50863e2d2f4c084.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
实现爬虫
[外链图片转存失败(img-G88je6rV-1563275786860)(https://upload-images.jianshu.io/upload_images/11158618-b25e8fd0117747a7.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
Promise.resolve
Promise.reject
Promise.race
class Confirm {
constructor() {
this.promise = new Promise( (resolve, reject) => {
this.confirmButton.onClick = resolve;
this.cancelButton.onClick = reject;
});
}
}
异步函数
async/await
[外链图片转存失败(img-uPT4NB5I-1563275786863)(https://upload-images.jianshu.io/upload_images/11158618-04ff4db56e06cf7b.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]
请点赞!因为你的鼓励是我写作的最大动力!
[外链图片转存失败(img-v0kSdgvF-1563275786868)(//upload-images.jianshu.io/upload_images/11158618-f0c11041a76563e7?imageMogr2/auto-orient/strip|imageView2/2/w/1240 “喜欢我就关注我”)]
吹逼交流群:711613774
[外链图片转存失败(img-GBd05T10-1563275786870)(//upload-images.jianshu.io/upload_images/11158618-d9d64fa290371ea5.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)]