Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

javascript - 异步/等待无法在jQuery each()中按预期方式工作(async/await not working as expected in jQuery each())

My async/await sample code not working properly.

(我的异步/等待示例代码无法正常工作。)

I am using jquery .each loop, along with Async/await functionality but not working as expected

(我正在使用jquery .each循环以及Async / await功能,但无法按预期工作)

I would expect the output to be:

(我希望输出为:)

one
John
July
Anja
two
done

However the actual output is:

(但是实际输出是:)

one
two
done
John
July
Anja

 $(document).ready(function() { function one() { return new Promise(resolve => { setTimeout(() => { console.log("one"); resolve(); }, 500); }); } function two() { return new Promise(resolve => { setTimeout(() => { console.log("two"); resolve(); }, 300); }); } function namePrint(name) { return new Promise(resolve => { setTimeout(() => { console.log(name); resolve(); }, 400); }); } async function msg() { try { await one(); $("#myTable tr").each(async function(index, item) { await namePrint($(this).find("#name").text()); }); await two(); console.log("done"); } catch (e) { console.log("Error:", e); } } msg(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody id="myTable"> <tr> <td id="name">John</td> <td>Doe</td> <td>[email protected]</td> </tr> <tr> <td id="name">July</td> <td>Dooley</td> <td>[email protected]</td> </tr> <tr> <td id="name">Anja</td> <td>Ravendale</td> <td>[email protected]</td> </tr> </tbody> </table> 

  ask by Mohammad Momtaz translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change nameprint time to 100. setTimeout is not an async function.so it won't wait for printing John july anja.

(将名称打印时间更改为100。setTimeout不是异步函数。因此它不会等待打印John july anja。)

So you have to adjust your settimeout function time.Or you can use sleep function using ES6 Promise.

(因此您必须调整settimeout函数的时间。也可以通过ES6 Promise使用睡眠功能。)

Every setimeout will create stack of functions to run which will run after time gets over.

(每个setimeout将创建要运行的函数堆栈,这些函数将在时间结束后运行。)

See if this helps.

(看看是否有帮助。)

 function namePrint(name) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(name);
        resolve();
      }, 100);
    });
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...