简体   繁体   English

JavaScript许诺/然后未按正确的顺序执行

[英]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. 从api获得成功响应后,它应仅显示“成功”消息。 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. 如果状态为200,那么您将设置一个以后success调用的承诺。

Regardless of what the status is (because it is outside of the if and you haven't used an else ) you always call error . 不管状态是什么(因为它在if之外,并且您没有使用else ),您总是会调用error

Presumably you just want to move return toastr.error('Failure'); 大概您只是想将return toastr.error('Failure'); into an else else

That's not how you setup promises. 那不是您设置诺言的方式。 Promises uses .then() . Promises使用.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. 许多系统(例如AJAX)发送多个消息以指示任务的进度。 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(){ '返回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');
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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