在Javascript中编写异步方法(在Node.js中运行代码)(Writing an asynchronous method in Javascript (Code run in Node.js)

编程入门 行业动态 更新时间:2024-10-22 05:11:29
在Javascript中编写异步方法(在Node.js中运行代码)(Writing an asynchronous method in Javascript (Code run in Node.js))

在下面的代码中,我试图理解编写异步JavaScript函数的概念。 要清楚我的假设:

调用函数logTest()。 它调用asyncTest(),传入log()函数。 但是,asyncTest()不直接调用log()。 相反,它将它传递给事件队列,以便在堆栈清除时调用。 在for循环完成之后,堆栈不应该清除,写入二十个“等待......”。 但是,控制台输出在for循环之前首先放置“async”行。 我在Node.js中运行了这段代码,其中console.log是一个同步函数。 有谁知道为什么“异步”线不是最后写的?

function asyncCall(method) { return setTimeout(method, 0); } function log(str) { console.log(str); } function logTest() { asyncCall(log("async")); for(var i = 0; i < 20; i++) { log("waiting..."); } } logTest();

In the following code, I'm attempting to understand the concept of writing asynchronous JavaScript functions. To be clear on my assumptions:

The function logTest() is called. It calls asyncTest(), passing in the log() function. However, asyncTest() doesn't call log() directly. Rather, it passes it to the event queue to be called when the stack clears. The stack shouldn't clear until after the for loop completes, writing twenty "waiting..."'s. However, the console output puts the "async" line first before the for loop. I ran this code in Node.js, in which console.log is a synchronous function. Does anyone know why the "async" line wasn't written last?

function asyncCall(method) { return setTimeout(method, 0); } function log(str) { console.log(str); } function logTest() { asyncCall(log("async")); for(var i = 0; i < 20; i++) { log("waiting..."); } } logTest();

最满意答案

那是因为你将log("async")而不是函数log传递给asyncCall 。

基本上,它执行log("async") (在执行asyncCall之前将“async”记录到控制台)。 调用的结果(由于log不返回任何内容而undefined )将传递给asyncCall 。 然后执行异步调用。

您可能希望将其更改为:

asyncCall(log.bind(null, "async"))

要么

asyncCall(function(){ log("async"); });

That's because you're passing the result of log("async") rather than the function log to asyncCall.

Basically, it executed log("async") (logging "async" to the console prior to executing asyncCall). The result of the call (which is undefined since log doesn't return anything) is passed to asyncCall. Then async call gets executed.

You may want to change that to:

asyncCall(log.bind(null, "async"))

or

asyncCall(function(){ log("async"); });

更多推荐

本文发布于:2023-08-04 02:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   方法   js   Node   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!