若想系统学习Promise可以阅读:阮一峰大神写的Promise对象,此篇记录常用用法。
Promise并行请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
const getA = new Promise((resolve, reject) => { setTimeout(function(){ resolve(2); }, 1000) }) .then(result => result)
const getB = new Promise((resolve, reject) => { setTimeout(function(){ reject('Error in getB'); }, 1000) }) .then(result => result)
Promise.all([getA, getB]).then(data=>{ console.log(data) }) .catch(e => console.log(e));
|
- getA和getB并行执行,然后输出结果。总是返回resolve结果
- 每一个promise自己处理错误
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
const getA = new Promise((resolve, reject) => { setTimeout(function(){ resolve(2); }, 1000) }) .then(result => result) .catch(e=>{
})
const getB = new Promise((resolve, reject) => { setTimeout(function(){ reject('Error in getB'); }, 1000) }) .then(result => result) .catch(e=>e)
Promise.all([getA, getB]).then(data=>{ console.log(data) }) .catch(e => console.log(e));
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| let tasks = []; for (let i = 1; i <= 5; i++) { tasks.push(i); };
let getDataBind = (func, params) => { return params.map( item => { return func.call(null, item) }) }
let getData = (page_no) => { let saveListData = JSON.parse(localStorage.getItem(this.props.saveListData)); let params = { page_no:page_no, ...saveListData.loadParams } return new Promise(resolve => { get(this.props.sortUrl, params, this, false).then(function (data) { resolve(data.result;); }); }) } Promise.all(this.getDataBind(this.getData, arrPage)) .then( resultArr => { resultArr = resultArr.flat(); console.log(resultArr) });
|