如何指定node.js函数的评估顺序?

下面,我试图在console.log(toObtain)之前评估im.identify ,但看起来console.log(toObtain)是在im.identify之后im.identify 。 我怎样才能确保函数的调用顺序是我希望它们被调用的?

 var toObtain; //I'm trying to set the value of this variable to features (inside the callback). var im = require('imagemagick'); im.identify('kittens.png', function(err, features){ if (err) throw err //console.log(features); toObtain = features; console.log(toObtain); //this prints { format: 'PNG', width: 400, height: 300, depth: 8 } }) console.log(toObtain); //This function call is evaluated BEFORE im.identify, which is exactly the opposite of what I wanted to do. 

asynchronous是指事物准备就绪(没有任何同步关系)。

这意味着,如果您希望打印或以其他方式操作在asynchronous函数内创build的值,则必须在其callback函数中执行此操作,因为这是值保证可用的唯一位置。

如果您想要订购多个活动以便它们一个接一个地发生,那么您需要应用以同步方式(一个接一个)“链接”asynchronous函数的各种技术之一,例如由caolan编写的asynchronous JavaScript库。

在你的例子中使用asynchronous,你会:

 var async=require('async'); var toObtain; async.series([ function(next){ // step one - call the function that sets toObtain im.identify('kittens.png', function(err, features){ if (err) throw err; toObtain = features; next(); // invoke the callback provided by async }); }, function(next){ // step two - display it console.log('the value of toObtain is: %s',toObtain.toString()); } ]); 

这是因为asynchronous库提供了一个特殊的callback函数,用于移动到当前操作完成时必须调用的系列中的下一个函数。

有关更多信息,请参阅asynchronous文档,包括如何通过next()callback传递值到系列中的下一个函数以及async.series()函数的结果。

asynchronous可以安装到您的应用程序使用:

 npm install async 

或全局的,所以它可以用于所有的nodejs应用程序,使用:

 npm install -g async 

这是节点的工作原理。 这是正常的asynchronous行为。

为了避免在使用节点的时候疯狂,重要的是把事情分解成每个都有特定目的的函数。 每个函数将根据需要调用下一个传递的参数。

 var im = require('imagemagick'); var identify = function () { im.identify('kittens.png', function(err, features){ doSomething(features) // call doSomething function passing features a parameter. }) }(); // this is the first function so it should self-execute. var doSomething = function (features) { var toObtain = features; console.log(toObtain) //or whatever you want to do with toObtain variable }; 

这是正常的,因为im.identify接缝是asynchronous的(它需要一个callback)。 因此,callback可以在下一行之后执行。

编辑:因此你必须把任何代码,用户获取您的callback,之后toObtain = features;