I'm not able to get my asynchronous code working with node.js
Trying both async and step libraries -- the code only returns the first function (doesn't seem to go through the rest). What am I doing wrong?
thanks!
var step = require('step');
step(
function f1(){
console.log('test1');
},
function f2(){
console.log('test2');
},
function finalize(err) {
if (err) { console.log(err);return;}
console.log('done with no problem');
}
);
or THIS:
var async = require('async');
async.series([
function f1(){
console.log('test1');
},
function f2(){
console.log('test2');
},
function finalize(err) {
if (err) { console.log(err);return;}
console.log('done with no problem');
}
]);
Asynchronous operations allow Node. js to serve multiple requests efficiently. An asynchronous call is initiated, and a callback is provided that is to be called later when the results are in. Between initiating the call and firing of the callback, other computations can take place.
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.
await can only be used in async functions. It is used for calling an async function and waits for it to resolve or reject. await blocks the execution of the code within the async function in which it is located.
The asynchronous function can be written in Node. js using 'async' preceding the function name. The asynchronous function returns implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event-loop.
Step.js is expecting callbacks for each step. Also the function that is using Step should callback with the result and not return it.
So let's say you have:
function pullData(id, callback){
dataSource.retrieve(id, function(err, data){
if(err) callback(err);
else callback(data);
});
}
Using Step would work like:
var step = require('step');
function getDataFromTwoSources(callback){
var data1,
data2;
step(
function pullData1(){
console.log('test1');
pullData(1, this);
},
function pullData2(err, data){
if(err) throw err;
data1 = data;
console.log('test2');
pullData(2, this);
},
function finalize(err, data) {
if(err)
callback(err);
else {
data2 = data;
var finalList = [data1, data2];
console.log('done with no problem');
callback(null, finalList);
}
}
);
};
This would get it to proceed through the steps.
Note that I personally prefer async for two reasons:
I can only speak to async
, but for that your anonymous functions in the array you pass to async.series
must call the callback
parameter that is passed into those functions when the function is done with its processing. As in:
async.series([
function(callback){
console.log('test1');
callback();
},
function(callback){
console.log('test2');
callback();
}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With