我如何访问返回的承诺的价值?
How do I access the value of a returned promise?
我确信我遗漏了一些关于同步性的明显和基本的东西,但我无法理解它应该如何工作...
$scope.foo=[];
getFoo(url) {
$scope.foo=$http.get(url).then(function (response) {
var foo = [];
//process response to get foo array. Console.log returns as expected here.
return foo;
});
}
这似乎只是将 $scope.foo
设置为 promise 对象。我错过了什么?我如何在其余代码中实际使用 promise 的结果?
而不是 return
ing foo
,您需要将赋值移动到回调中:
getFoo(url) {
$http.get(url).then(function (response) {
var foo = [];
// process response to get foo array...
$scope.foo = foo;
});
}
使用 promises,return
由 .then()
回调编辑的值将仅可用于另一个 .then()
回调,当它们链接在一起时:
$http.get(url).then(function (response) {
var foo = [];
// process response to get foo array...
return foo;
}).then(function (foo) {
$scope.foo = foo;
});
我确信我遗漏了一些关于同步性的明显和基本的东西,但我无法理解它应该如何工作...
$scope.foo=[];
getFoo(url) {
$scope.foo=$http.get(url).then(function (response) {
var foo = [];
//process response to get foo array. Console.log returns as expected here.
return foo;
});
}
这似乎只是将 $scope.foo
设置为 promise 对象。我错过了什么?我如何在其余代码中实际使用 promise 的结果?
而不是 return
ing foo
,您需要将赋值移动到回调中:
getFoo(url) {
$http.get(url).then(function (response) {
var foo = [];
// process response to get foo array...
$scope.foo = foo;
});
}
使用 promises,return
由 .then()
回调编辑的值将仅可用于另一个 .then()
回调,当它们链接在一起时:
$http.get(url).then(function (response) {
var foo = [];
// process response to get foo array...
return foo;
}).then(function (foo) {
$scope.foo = foo;
});