简体   繁体   中英

Get result of rest request instead of response?

I have the following function in my controller.

RestRequestsSrvc.getUserDetail()
  .then(
    function (response) {
      $scope.user.userDetail = response;
    },
    function (error) {
      // TODO
    });

If I type

console.log(RestRequestsSrvc.getUserDetail());

the console logs a promise. I want to set a variable the the response. How can I modify my code so that I get the response instead of a promise?

Return a promise because your request is async.

You should wait the response,

Putting the console.log inside the callback function should print your info.

RestRequestsSrvc.getUserDetail()
  .then(
    function (response) {
      $scope.user.userDetail = response;
      console.log(response);
    },
    function (error) {
      // TODO
    });

You can do the console.log into the promise .then

RestRequestsSrvc.getUserDetail()
  .then(
    function (response) {
      $scope.user.userDetail = response;
      console.log(response);
    },
    function (error) {
      // TODO
    });

The thing is that when you call the function it will be executed but will not wait for the result, that's why you get a promise. The .then stuff is called once the request is done executing. That's where you handle your success or error callbacks.

Requests to the server are asynchronous, meaning that you must handle the response inside the callback.

You could use async false flag but this is not recommended if you have independent modules that executed later in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM