【问题标题】:Is it possible to use a sync promise sleep inside of jQuery.each()?是否可以在 jQuery.each() 中使用同步承诺睡眠?
【发布时间】:2020-06-20 20:16:50
【问题描述】:

基本上是这样。我想在同步函数中使用 jQuery 的每个函数。 不过,据我所知。它不起作用,因为每个函数只是检查返回值是否为 false 以中断循环。它不检查它是否是一个承诺,然后将其设置为等待它被解决。有没有一种简单的方法可以让 jQuery 的每个函数与 Promise 同步?

我目前有一个替代方法,即创建一个迭代元素的 for 循环,但它写起来有点长,所以我想尽可能避免这种情况。

这里是它的一个小提琴: https://jsfiddle.net/3pcvqswn/2/

function sleep(ms)
{
    return new Promise(resolve => setTimeout(resolve, ms));
}

$(document).ready(function()
{
    (async () =>
  {
    console.log("This method works, but its lengthy to write");
    var elements = $("div");

    for(var index = 0; index < elements.length; index++)
    {
        var el = $(elements.eq(index));

        console.log("The content is: " + el.text());

      await sleep(1000);
        }

    console.log("This method doesn't work, but its easier to write");
    $("div").each(async (index, el) =>
    {
        console.log("The content is: " + $(el).text());

      // doesn't wait
      await sleep(1000);
    });
  })();
});

我决定使用for of,但同时拥有索引和元素回调的更准确的解决方案是

  Object.entries($("div")).forEach(async ([index, el]) =>
  {
    console.log("row ", index, el);
  });

【问题讨论】:

    标签: javascript jquery asynchronous promise each


    【解决方案1】:

    否 - jQuery 的 .each 与 forEach 的工作方式类似。每个回调都会一个接一个地被触发,如果回调返回一个 Promise(比如它是一个异步函数),它不会被等待 - 它的工作原理类似于

    callback();
    callback();
    callback();
    

    除非回调中的某些内容阻塞(如果您使用体面的编程实践,则不应该这样做),回调中的任何异步初始化都不会导致进一步的回调等待该异步操作完成.

    但是 jQuery 对象是可迭代的,所以使用简洁的 for..of 来迭代元素是微不足道的:

    const sleep = ms => new Promise(res => setTimeout(res, ms));
    
    (async () => {
      for (const elm of $("div")) {
        console.log("The content is: " + $(elm).text());
        await sleep(1000);
      }
    })();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>text 1</div>
    <div>text 2</div>
    <div>text 3</div>

    IMO 一点也不冗长。

    为了在循环中使用await,循环必须是for 循环(for..in、for..of 或 for(let i = ...),或者需要构造loop的迭代机制,使其等待最后一个回调解决,比如用reduce:

    const sleep = ms => new Promise(res => setTimeout(res, ms));
    
    [...$("div")].reduce(async (lastProm, elm) => {
      await lastProm;
      console.log("The content is: " + $(elm).text());
      await sleep(1000);
    }, Promise.resolve());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>text 1</div>
    <div>text 2</div>
    <div>text 3</div>

    几乎不值得一提的旁注 - 我之前说过在 .each 中使用 await 是行不通的

    除非回调中的某些内容阻塞(如果您使用体面的编程实践,则不应该这样做)

    如果您编写了一个昂贵且愚蠢的 sleep 阻塞版本,它会消耗所有资源,直到到达下一秒,“可能”在循环内等待,但永远不应该这样做:

    const sleep = ms => {
      const now = Date.now();
      while (Date.now() - now < ms) {}
    }
    

    正确使用 Promise 会好得多。

    【讨论】:

    • 我同意一切,除了你有while循环。 setTimeout 调用是非阻塞的,而 while 循环在每个滴答声中执行一个空循环,使您的 CPU 达到最大值。
    • 这就是为什么我说它几乎不值得一提。从技术上讲,它可以满足您的需求 - 在 jQuery 的 each 中等待,因为没有其他东西可以完成这项工作 - 但这是一个可怕的想法,就像我说的那样,永远不应该使用。
    【解决方案2】:

    您不能强制$.each 连续运行(一个接一个)。它“同时”运行每个元素的函数。一种选择是编写您自己的 each 函数,该函数只执行您在问题中编写的较长版本:

    const serialEach = async (f, elements) => {
       for(let index = 0; index < elements.length; index++) {
           const el = $(elements.eq(index))
    
           await f(el)
        }
    }
    

    然后你可以这样运行它:

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }
    
    $(document).ready(() => {
        const elements = $("div")
    
        serialEach(async (el) => {
            console.log("The content is: " + el.text())
    
            await sleep(1000)
        }, elements)
    })
    

    注意serialEach 返回一个promise,所以它会立即返回,并且你在serialEach 调用之后的任何代码都会执行,即使serialEach 正在迭代你的元素。如果您想在继续之前等待该迭代完成,您可以只使用await serialEach(并让您的$.ready 回调async)。

    【讨论】:

      【解决方案3】:

      我不建议为此使用 .each。无论是否异步,该函数都会被执行。但是通过编程,您可以发挥创造力。

      //code
      
      function sleep(ms) {
          return new Promise(resolve => setTimeout(resolve, ms));
      }
      
      let promise = Promise.resolve();
      $("div").each((index, el) => {
        promise = promise.then(async () => {
          console.log("The content is: " + $(el).text());
      
          await sleep(1000);
        });
      });
      
      await promise;
      
      //code
      

      【讨论】:

        猜你喜欢
        • 2021-09-05
        • 2015-07-25
        • 2020-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        相关资源
        最近更新 更多