You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionparamTest(){returnnewPromise((resolve,reject)=>{letnumber=Math.ceil(Math.random()*10);//生成1-10的随机数if(number<5){resolve(number);}else{reject('out of range');}})}paramTest().then((number)=>{console.log('resolved');console.log(number);},(reason)=>{console.log('rejected');console.log(reason);})
Promise
基本概念
Promise
接收一个函数作为参数,函数有两个参数,resolve
和reject
分别表示异步操作执行后成功的回调函数和失败的回调函数。Promise
实例后马上执行。所以通常采用一个函数包含它runAsync()
执行完调用then
方法,then()
就相当于我们之前写的回调函数。resolve 和 reject
Promise
有三种状态:pending
(进行中)、fulfilled
(已成功)和rejected
(已失败)paramTest()
例子有两种情况:number < 5
时,我们认为是成功情况,将状态从pending
变为fulfilled
number >= 5
时,我们认为是失败情况,将状态从pending
变为rejected
catch的用法
catch
方法其实就是.then(null, rejection)
的别名,也是用来处理失败失败的回调函数,但是还有一个作用:当resolve
回调中如果出现错误了,不会堵塞,会执行catch
中的回调。all的用法
race的用法
两个有用的方法
示例源代码(F12查看)
Promise实践:使用Promise实现图片预加载,并展示加载进度
参考
http://es6.ruanyifeng.com/#docs/promise
http://www.cnblogs.com/lvdabao/p/es6-promise-1.html
The text was updated successfully, but these errors were encountered: