参考文章:廖雪峰的官方网站:JavaScript:promise章节 ES6 Promise用法小结
为了解决多个异步操作存在依赖关系的调用问题,考虑使用promise方法。比如函数func2依赖函数func1的接口数据,常规的方法是把func2放到func1的回调函数里执行。但如果出现多个依赖就得多层嵌套,显得麻烦。这时候promise就非常方便了。
方法速记:
1、then、catch
func1(){ return new Promise(function(resolve,reject){ this.http.get('/dintegrationapi/comCodeSet/getItems').subscribe((result: any) => { if (result.is_success) { resolve(result) } else { reject(result) } }) }) }
func1().then(function(data){
func2();
}).catch(function(data){
console.log(data)
})
resolve(result)为传递给then的参数,reject(result)为传递给catch的参数。
2、all
// 同时执行p1和p2,并在它们都完成后执行then: Promise.all([p1, p2]).then(function (results) { console.log(results); // 获得一个Array: ['P1', 'P2'] });
p1、p2都是promise 函数,promise.all会把P1函数和P2函数的结果整合到一个数组里面。