查看更多
$q(function resolver (resolve, reject) {})
var iWantResolve = true;
function es6promise() {
return $q(function (resolve, reject) {
$timeout(function () {
if (iWantResolve) {
resolve("es6promise resolved");
} else {
reject("es6promise reject");
}
}, 1000)
})
}
- promise.then(successCb, errCb, notifyCb)
- 其中successCb 将在 promise resolve 后被调用, errCb 将在 promise reject 后被调
- notifyCb 将在 deferred.notify 后被调用, 可以多次调用
- promise.catch == promise.then(null, errCb), 用于处理之前没有被处理的 rejected promise
- promise.finally 将最后被调用, 一般用于资源释放的清理操作
es6promise()
.then(function (data) {
console.log(data);
})
.catch(function (err) {
console.log(err);
});
// if(iWantResolve == true) output: es6promise resolved
// if(iWantResolve = false) output: es6promise reject
$q.defer()
function commonJsPromise() {
var deferred = $q.defer();
$timeout(function () {
deferred.notify("commonJS notify");
if (iWantResolve) {
deferred.resolve("commonJS resolved");
} else {
deferred.reject("commonJS reject");
}
}, 500);
return deferred.promise;
}
commonJsPromise()
.then(function /** success callback**/(data) {
console.log(data);
}, function /** error callback **/ (err) {
console.log(err);
}, function /** progress callback **/ (update) {
console.log(update);
});