Promise代表一个未来值,通常是异步操作的未来结果,并允许我们定义一旦该值可用或发生错误时会发生什么。
参考
var promise = asyncFunction(parameters);
promise.then(
function (result) {
// Do Something with the result
},
function (error) {
// Handle error (exception, etc).
});
您可以使用实用程序方法用 Promise 包装任何值$q.when()
。
- $q.when(promise) → 承诺
- $q.when(nonPromise) → 一个新的承诺,它将
- 异步解析为给定值 nonPromise。
===============================
在您的示例中:
HTML
<div ng-app ng-controller="testController">
<p>Direct property: {{ property }}</p>
<p>Function returning property: {{ getProperty() }}</p>
<p>Direct promise: {{ promise }}</p>
<p>Function returning promise: {{ out }}</p>
</div>
JS
function testController($scope, $q) {
var deferred = $q.defer();
deferred.resolve('some lazy text');
$scope.promise = deferred.promise;
$scope.out = $scope.promise.then(function (result) {
console.log(result);
return result;
});
$scope.property = 'some text';
$scope.getProperty = function () {
return $scope.property;
};
}
演示小提琴