Below, I tried to evaluate the im.identify before console.log(toObtain), but it appears that console.log(toObtain) was called after im.identify. How can I make sure that the functions are called in exactly the order that I want them to be called?
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 means that things occur when they are ready (without any synchronous relationship to each other.)
This implies that if you wish to print or otherwise operate on a value created within an asynchronous function, you MUST do so in its callback since that is the only place that the value is guaranteed to be available.
If you wish to order multiple activities so they occur one after another, you’ll need to apply one of the various techniques which “chain” asynchronous functions in a synchronous way (one after another) such as the async javascript library written by caolan.
Using async in your example, you would:
The reason this works is because the async library provides a special callback that is used to move to the next function in the series which must be called when the current action has completed.
See the async documentation for further info, including how to pass values through the next() callback to the next function in the series and as the result of the async.series() function.
async can be installed to your application using:
or globally, so it is available to all your nodejs applications, using: