异步数组处理逐个处理返回结果

使用bluebird.js实现

by Mike Lin

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.7/bluebird.min.js"></script>

JavaScript

function async_sum(num) {
	return new Promise((resolve, reject)=>{
		setTimeout(()=>{
			return resolve("success--"+ (1 + num));
		},500);
	});
}

function async_sum_with_error(num) {
	return new Promise((resolve, reject)=>{
		setTimeout(()=>{
			return reject("error--"+ (1 + num));
		},500);
	});
}

var fun1 = async_sum(1);
var fun2 = async_sum_with_error(2);
var fun3 = async_sum_with_error(3);
var fun4 = async_sum(4);
var arr2 = [fun1, fun2, fun3, fun4];

Promise.all(arr2.map((promise) => {
	return promise.reflect()
}))
.each((inspection, index) => {
  if (inspection.isFulfilled()) {
    console.log("A promise in the array was fulfilled with", inspection.value());
  } else {
    console.error("A promise in the array was rejected with", inspection.reason());
  }
})
.then(result => {
	console.log('Promise.all--',result)
  throw new Error('throw new error')
})
.catch((err) => {
  console.log('Promise catch error: ', err)
})