简体   繁体   English

Node.js代码执行顺序

[英]Node.js code execution order

First day at programming in Node today. 今天在Node编程的第一天。 I've been getting along nicely all day but have some across something weird. 我整天相处得很好,但有些奇怪的事情。 I'm probably not understanding Node's asynchronism or something. 我可能不了解Node的异步性。

I have a function that executes a shell command: 我有一个执行shell命令的函数:

function puts( error, stdout, stderr ) { sys.puts( stdout ); }

Then I execute some commands: 然后我执行一些命令:

exec( "foo", puts );
myarr.keys( "mykey", function ( err, replies ) {
   replies.forEach( function ( reply, i ) {
      exec( "bar" );
   });
});
exec( "fuzz", puts );
exec( "buzz", puts );

so the two last things that are meant to be executed are fuzz and then buzz . 因此,应该执行的最后两件事是fuzz ,然后是buzz However, it seems that fuzz and buzz happen at some random point in the loop and bar is the thing that gets printed last (sometimes). 但是, fuzzbuzz似乎发生在循环中的某个随机点,而bar是最后(有时)打印的东西。 myarr is an array that I build by connecting to a Redis database. myarr是我通过连接到Redis数据库构建的数组。

Do I have to force Node to do the loop synchronously or something? 我是否必须强制Node同步执行循环? I am using Redis clients in the code.. could these cause problems? 我在代码中使用Redis客户..这些会引起问题吗? Any ideas? 有任何想法吗? Many thanks :). 非常感谢 :)。

myarr.keys() takes a callback, which won't be executed until the redis query completes. myarr.keys()进行回调,直到redis查询完成后才会执行。

If you need 'fuzz' and 'buzz' to execute after then, and after the loop, move them into the callback function like so: 如果在此之后和循环之后需要执行“ fuzz”和“ buzz”,则将它们移动到回调函数中,如下所示:

exec( "foo", puts );
myarr.keys( "mykey", function ( err, replies ) {
   replies.forEach( function ( reply, i ) {
      exec( "bar" );
   });
   exec( "fuzz", puts );
   exec( "buzz", puts );
});

It's important to note that myarr.keys() returns instantly (well, after it has sent the query to redis). 重要的是要注意myarr.keys()立即返回(好吧,它已将查询发送到redis之后)。 This allows you to continue with other stuff, and not block the process. 这使您可以继续处理其他内容,而不会阻止该过程。 The callback function is how you specify code to handle the reply from redis, which could come at any point in the future. 回调函数是您如何指定代码来处理来自redis的回复的方式,将来可能会出现此情况。

using exec causes these operations to run asynchronously. 使用exec会使这些操作异步运行。 You might want to look into the fs package for synchronous equivalents. 您可能需要查看fs包中的同步等效项。 Alternatively, you might want to look into a way to stack your commands before executing them all in one batch 或者,您可能想研究一种将命令堆叠起来的方法,然后再批量执行所有命令

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

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