功能处理完成后的Javascript警报

时间:2017-07-18 05:29:34

标签: javascript

这是Javascript代码:

if (selected && this.env.contentframe && !list.multi_selecting)
this.preview_timer = setTimeout(function() {
  ref.msglist_get_preview();
  alert('done');
}, list.dblclick_time);
else if (this.env.contentframe)
  this.show_contentframe(false);

这是msglist_get_preview()功能代码:

this.msglist_get_preview = function()
{
    var uid = this.get_single_uid();
    if (uid && this.env.contentframe && !this.drag_active)
      this.show_message(uid, false, true);
  };

低于show_message()功能:

  this.show_message = function(id, safe, preview)
  {
    if (!id)
      return;

    var win, target = window,
      url = this.params_from_uid(id, {_caps: this.browser_capabilities()});

    if (preview && (win = this.get_frame_window(this.env.contentframe))) {
      target = win;
      url._framed = 1;
    }

url = this.url(preview ? 'preview': 'show', url);
this.location_href(url, target, true);
}:

我希望在函数ref.msglist_get_preview();进程完成时发出警报。我已经尝试了,但每次出现警报然后功能加载。

我怎样才能做到这一点?

提前致谢。

1 个答案:

答案 0 :(得分:1)

setTimeout(function(){...},0)简单地将代码排队,以便在当前调用堆栈执行完毕后运行。所以你面临的问题是因为你的> ref.msglist_get_preview();也正在做异步任务,这就是为什么它在setTimeout之后排队,因此你得到警报('完成');首先,然后你的方法执行。 以下是解释相同的例子:



this.preview_timer = setTimeout(function() {
abc();
  alert('done');
}, 500);

function abc(){
 setTimeout(function(){
 alert('abc');
 },100) 
} 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

此警报(&#39; abc&#39;)将在提醒后执行(&#39;已完成&#39;)

对于您的问题,您可以使用javascript promises。以下代码应解决您的问题:

 if (selected && this.env.contentframe && !list.multi_selecting)
this.preview_timer = setTimeout(function() {
  ref.msglist_get_preview().then(function(){
    alert('done');
  })
}, list.dblclick_time);
else if (this.env.contentframe)
  this.show_contentframe(false);

function msglist_get_preview() {
   return new Promise(function(resolve, reject) {
         setTimeout((function() {
            alert('msglist_get_preview worked');
            resolve("Stuff worked!");
        }), 1000);
    });
}