简体   繁体   中英

Javascript promise/then not executing in correct order

Here's the code:

vm.saveData = function(data) {

             demoService.saveData(data, function(response) {
                if (response.status === 200) {
                    principal.identity(true).then(function() {
                        $state.reload();
                        return toastr.success('Success');
                    });

                }
                return toastr.error('Failure');
            });
}

On getting success response from the api, it should display only the 'success' message. But, instead it displays the 'failure' message first and then the 'success' message. What am I doing wrong? Do I have to put a timeout or is there something which I'm missing here?

If the status is 200 then you set up a promise to call success later on.

Regardless of what the status is (because it is outside of the if and you haven't used an else ) you always call error .

Presumably you just want to move return toastr.error('Failure'); into an else

That's not how you setup promises. Promises uses .then() . You are simply using passing the function in as a callback.

vm.saveData = function(data) {

  demoService
    .saveData(data)
    .then(success, error);

  function success(response) {
    principal.identity(true).then(function() {
      $state.reload();
      return toastr.success('Success');
    });
  }

  function error(response) {
    return toastr.error('Failure');
  }
};

Many systems such as AJAX send multiple messages to indicate progress in the task. You want to ignore the earlier messages. The failure message is from the earlier events while the action is incomplete.

I found out my mistake. Adding 'return' resolved the issue.

'return principal.identity(true).then(function(){

//do something here

});'

vm.saveData = function(data) {

             demoService.saveData(data, function(response) {
                if (response.status === 200) {
                    return principal.identity(true).then(function() {
                        $state.reload();
                        return toastr.success('Success');
                    });

                }
                return toastr.error('Failure');
            });
}

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