简体   繁体   English

等待功能完成

[英]waiting a function to complete

I have 2 functions. 我有2个功能。 The second one is faster than the first one,how could the function wait to complete first one's work? 第二个比第一个快,功能如何等待完成第一个工作?

function1(); // slow 

function2(); // fast

JavaScript is imperative and single-threaded, it just works like this. JavaScript是祈使句和单线程的,它只是工作原理是这样。 function2() won't start until function1() finishes. function2()function1()完成后才会启动。

If by slow you mean calling asynchronously some external service via AJAX, then we're talking. 如果慢一点意味着通过AJAX异步调用一些外部服务,那么我们正在谈论。 function1() must provide some sort of callback so that when asynchronous request finishes, function2() is called: function1()必须提供某种回调,以便在异步请求完成时function2()

function1(function2);

The implementation is trivial, eg using jQuery: 实现是微不足道的,例如使用jQuery:

function function1(callback) {
  $.ajax({url: 'some-url'}).done(callback);
}

You must be using some AJAX request. 您必须使用某些AJAX请求。 So, after ajax complete call callback function like: 所以,在ajax完成调用回调函数之后:

function1 = new function(callback) {
    $.ajax({...}).done(callback());
}

function1(function2);

If functions are to be called asynchronously, aside from the obvious callback approach, their sequencing could be based on the events framework. 如果要异步调用函数,除了明显的回调方法之外,它们的排序可以基于事件框架。 You could add an event listener with function1 as a handler, and trigger that event within function2. 您可以使用function1作为处理程序添加事件侦听器,并在function2中触发该事件。

如果你的呼叫功能接着另一个,则它将完成第一个功能,无论是慢速还是快速。

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

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