Primise 总结 js
回调
-
同步回调
func add(a,b,func){ func(a+b) }; console.log('start'); add(1,2,v=>console.log(v)); console.log('end');
-
异步回调
func add(a,b,func){ setTimeout(()=>func(a+b),1000); }; console.log('start'); add(1,2,v=>console.log(v)); console.log('end');3.
-
回调
```javascript
// 嵌套回调
func1(function(v1)) {
func2(function(v2)){
func3(function(v3)){
console.log(v1+v2+v3);
}
}
}
// Promise 回调
func1().then(function(){
return v1;
}).then(function(obj){
return v1+obj;
}).then(function(obj){
return v3 + obj;
})
```
Promise 使用
-
resolve & reject
promise构造函数生成Promise对象,入参函数resolve,reject
var promise = new Promise(function(resolve,reject){ // if succ resolve('succ'); // if err reject('err'); })
-
Fulfilled & Rejected
Promise对象一开始是Pending的准备状态
执行了
resolve()
,状态变为onFulfilled
状态执行了
reject()
,状态变为onRejected
状态 -
便捷构造方法
Promise.resolve(1); // == new Promise((resolve) => resolve(1));
Promise.reject(new Error("BOOM")) // === new Promise((resolve, reject) => reject(new Error("BOOM")));
-
异常捕获 catch
catch
方法可以捕获到then
中抛出的错误var promise = Promise.resolve(); promise.then(function() { return 'success'; }).then(function (success) { console.log(success); throw new Error("Another BOOM!"); }).catch(function (error) { console.log(error); // 可以正常捕捉到异常 });
网友评论