查看更多
$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);
});
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者