- 基础写法
var promise = new Promise(function ( resolve, reject ){
//do sth
resolve("success");
});
promise.then(function (value){
console.log(value);//success
}, function(err){
console.log(err);//reject执行
},)
如果只想对异常处理,可以采用<code>promise.then( undefined, onRejected )</code>or<code>promise.catch( onRejected )</code>
- return a Promise对象
function asyncFunction() {
return new Promise(function ( resolve, reject ) {
setTimeout( function () {
reject("error");
} , 16);
});
}
asyncFunction().then( undefined, function (err) {
console.log(err);//error
} )
========================================================
function getUrl(URL){
return new Promise ( function ( resolve, reject ){
var req = new XMLHttpRequest();
req.open("GET", URL, true);
req.onload = function () {
if ( req.status == 200 ){
resolve( req.responseText );
} else {
reject( new Error( req.statusText ) );
}
};
req.onerror = function () {
reject( new Error( req.statusText ) );
};
req.send();
} )
}
//running
var URL = "http://httpbin.org/get";
getUrl(URL).then( function onFulfilled ( value ) {
console.log(value);
}).catch( function onRejected ( error ){
console.error(error);
});
- Promise的处理流程
三状态
- Settled不变的
- "has-resolution"resolve成功
- "has-rejection"reject失败
- "unresolved"pending等待
- promise chain
function taskA() {
console.log("Task A");
}
function taskB() {
console.log("Task B");
}
function onRejected(error) {
console.log("Catch Error: A or B", error);
}
function finalTask() {
console.log("Final Task");
}
var promise = Promise.resolve();
promise
.then(taskA)
.then(taskB)
.catch(onRejected)
.then(finalTask);
======log======
Task A
Task B
Final Task
- Promise和数组——Promise.all
// `delay`毫秒后执行resolve
function timerPromisefy(delay) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(delay);
}, delay);
});
}
var startDate = Date.now();
// 所有promise变为resolve后程序退出
Promise.all([
timerPromisefy(1),
timerPromisefy(32),
timerPromisefy(64),
timerPromisefy(128)
]).then(function (values) {
console.log(Date.now() - startDate + 'ms');
// 約128ms
console.log(values); // [1,32,64,128]
});
//======log=====等待所有resolve完成后输出
131ms
1,32,64,128
- Promise和数组——Promise.race
Promise.all在接收到的所有的对象promise都变为 FulFilled 或者 Rejected 状态之后才会继续进行后面的处理,与之相对的是 Promise.race只要有一个promise对象进入FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理。
参考
AngularJS+LeanCloud+promise.all+echarts
var OPTIONS =["其他问题","车辆问题"];
var conditions = [];
$scope.sum = 0;
$scope.resData = [];
for(index in OPTIONS){
var condition = {
index:index,
opts:OPTIONS[index]
}
conditions.push(condition);
}
var promises = [];
angular.forEach(conditions , function (condition) {
var deferred = $q.defer();
var query = new AV.Query("Feedback");
query.equalTo("reason", condition.opts)
query.count().then(function (count) {
$scope.sum += count;
$scope.resData.push({
index:condition.index,
datax:OPTIONS[condition.index],
datay:count
})
deferred.resolve();
}, function (error) {
deferred.reject();
});
promises.push(deferred.promise);
})
$q.all(promises).then(function () {
$scope.resData.sort(function (a,b) {return a.index-b.index;})
$scope.makeChart($scope.resData,"pie");
})
网友评论