promise基础
来源:互联网 发布:谭铁牛 人工智能 编辑:程序博客网 时间:2024/06/15 22:02
promise简介:
Promise的出现,原本是为了解决回调地狱的问题.
通过把异步中使用回调函数的场景改为了.then()
、.catch()
等函数链式调用的方式。基于promise
我们可以把复杂的异步回调处理方式进行模块化。
promise原理:
其实promise
原理说起来并不难,它内部有三个状态,分别是pending
,fulfilled
和rejected
。
pending
是对象创建后的初始状态,当对象fulfill
(成功)时变为fulfilled
,当对象reject
(失败)时变为rejected
。不可逆向,且一旦状态改变就不会再变
promise使用:
Promise
对象拥有两个实例方法then()
和catch()
。
then
方法可以接收两个参数, 第一个参数会添加到fulfill
时调用的数组中,第二个参数添加到reject
时调用的数组中。当promise
状态fulfill
时,会把resolve(value)
中的value
值传给调用的函数中,同理,当promise
状态reject
时,会把reject(reason)
中的reason
值传给调用的函数。例:
promise例子:
//例子--模仿去读取一个jsonasync function asyncReadFile(int){ console.log(int); //打印1let result = await new Promise((resolve,reject)=> { console.log(2); //打印2ajax({ method: 'get', url: './file.json', success(response) { console.log(response); //打印结果 resolve('resolved'); }, fail(err) { reject(err); } });}).then((msg)=>{console.log(msg+'!!!')}); //成功打印出resolved!!! //result的值是await内部通过resolve传出来的值 console.log(3); //打印3};asyncReadFile(1).then((msg='msg')=>{console.log(msg+'1');return 'msg'+'1'}) //打印msg1 .then((msg)=>{console.log(msg+'2');return msg+'2'}) //打印msg12 .then((msg)=>{console.log(msg+'3');throw new Error('404');return msg+'3'}) //打印msg123 .catch((err)=>{console.error('错误是'+err)}); //打印'错误是404'结果如下:
promise注意点:
1.then
方法会返回一个新的promise
,下面的例子中p == p1
将返回false
,说明p1
是一个全新的对象。虽然它也是链式调用的,它是在新的对象上添加成功或失败的回调,这与jQuery
中的链式调用不同。
2. 如果promise.then(undefined,fnFail).then(fnSuccess)中resolve()调用成功函数 , 可以调用到fnSuccess函数 , 同理在reject中也可以这么执行. 当对应的参数不为函数时,会将前一promise
的状态和值传递下去。
3.所以我们可以在多个then
之后添加一个catch
方法,这样前面只要reject
或抛出异常,都会被最后的catch
方法处理。
- promise基础
- Promise 之基础篇
- es6基础回顾--Promise
- JavaScript基础之Promise
- JQuery的Promise详解(一):Promise基础
- JQuery的Promise详解 : Promise基础
- 剖析 Promise 之基础篇
- promise
- Promise
- Promise
- Promise
- Promise
- Promise
- Promise
- promise
- promise
- promise
- promise
- ROS相机数据转LaserScan
- 欢迎使用CSDN-markdown编辑器
- C#对象的浅拷贝、序列化深拷贝
- csv文件中的数据导入到oracle数据库中的sqlldr 和 pl/sql 的Text Importer方法
- 就这样一不小心,Python就火了
- promise基础
- 三种 mongodb 的驱动库的对比
- xml学习笔记②PHP DOM--对xml文件进行更新操作
- HttpClient 4.3连接池参数配置及源码解读
- Android 6.0 WRITE_SETTINGS权限问题
- 跟随手指移动的小球
- 15. 3Sum
- 2017-12-14 乱入一道C++类的学习的题(静态数据成员初始化)
- KeyStore 和 TrustStore