且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取异步函数的返回值?

更新时间:2022-06-14 03:15:06

异步调用无法按照您的思维方式(同步方式)工作.服务器调用它们后,它们不会立即返回值.您必须等到服务器响应请求.

Asynchronous call doesn't work the way you are thinking(synchronous way). They doesn't return a value as soon as server you call them. You have to wait till server respond to request.

在这里就像您 console.log 一样,执行 allBrands 函数,该函数返回 promise 对象(好像是 $ resource 承诺),那就可以了.而且,您可以在诺言对象到达后立即看到您的响应.我想说您应该在您的Promise对象上使用 .then ,在这里您可以从API返回数据.

Over here as you did console.log the allBrands function which return promise object(seems like $resource promise), that is getting consoled. And you can see your response in the promise object as soon as it arrives. I'd say you should use .then over your promise object where you can just get a data returned from API.

$scope.allBrands().then(successCB(states){
   $scope.states = states;
   console.log(states);
}, errorCB(error){
   console.log(error)
})