仅在.each()完成后才继续执行 [英] Continue Execution Only After .each() Completes

查看:92
本文介绍了仅在.each()完成后才继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种仅在.each()完成执行后才调用函数的方法.在下面的示例中,如何确保postPreparation()$('.element').each()完成后立即运行?

I am looking for a way to call a function only after .each() finishes its execution. In the example below, how to make sure that postPreparation() runs immediately after $('.element').each() completes?

$('.element').each(function() {
  /** 
   * 'prepareLayer()' is a complex function that takes a while to complete and,
   *  as in this construct, needs to be invoked for each matched element. Basically,
   * 'prepareLayer()' adds a lot of new HTML elements to the page.
   */   
  prepareLayer();
});

/**
 * Ideally, this should immediately run _after_ the above function completes
 * i.e. after each '.element' finishes running prepareLayer().
 *
 * 'postPreparation()' needs to attach some event handlers for the new HTML elements
 * created in 'prepareLayer()'.
 */
postPreparation();

从技术上讲,我正在寻找一种调用.each()的回调函数的方法.

Technically, I am looking for a way to invoke a callback function for .each().

注意:在以上示例中,我刚刚确认postPreparation()仅在.each()完成后才执行.问题是我的prepareLayer()使用AJAX构建了新的HTML元素,因此each()提前返回.正如@Alnitak所建议的那样,异步AJAX请求不会阻止.each()过早返回.

NOTE: I just confirmed, in the example above, that postPreparation() will execute only after .each() completes. The problem was my prepareLayer() builds the new HTML elements using AJAX, so each() returns prematurly. As suggested by @Alnitak, an asynchronous AJAX request wouldn't stop .each() from returning prematurely.

推荐答案

除非prepareLayer()正在执行异步操作(例如AJAX或动画),否则直到prepareLayer()完成并且您的代码已经可以满足您的要求.

Unless prepareLayer() is doing something asynchronous (e.g. AJAX, or animation) each pass around the loop can't terminate until prepareLayer() has finished anyway and your code will already do what you want.

FWIW,如果您现有的.each循环中没有其他操作或参数,则实际上您只需要编写以下内容:

FWIW, if there are no additional operations or parameters in your existing .each loop you actually just need to write this:

$('.element').each(prepareLayer);

即不需要其他的匿名函数包装器.

i.e. there's no need for the additional anonymous function wrapper.

另一方面,如果它正在做异步操作,请使用延迟对象:

On the other hand, if it's doing something asynchronous, use deferred objects:

var def = [];
$('.element').each(function() {
    // have prepareLayer return a _promise_ to return
    def.push(prepareLayer());
});

function prepareLayer() {
    var jqxhr = $.get(..., function() {
        // do stuff with content
    });
    return jqxhr;
}

// use "when" to call "postPreparation" once every
// promise has been resolved
$.when.apply($, def).done(postPreparation);

这篇关于仅在.each()完成后才继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆