Below code I am using.
createGroupsForZones(var1, arr)
.then(createGroupsForRegions(var3, arr))
Here arr contains 2 elements
const createGroupsForZones = function (var1, arr) {
return new Promise(function (resolve, reject) {
let json;
async.forEachLimit(arr, 1, function (eachZone, callback) {
abc(code, json, false, function (err) {
if (err) {
logger.error(`Error while processing group zone:: ${err.stack}`);
return cb(err);
}
logger.info('Successfully processed Zones');
return cb();
})
}, function (err) {
if (err) {
return reject(err);
}
return resolve();
})
})
Here arr contains 2 elements
const createGroupsForRegions = function (var1, arr) {
return new Promise(function (resolve, reject) {
let json;
async.forEachLimit(arr, 1, function (eachZone, callback) {
def(code, json, false, function (err) {
if (err) {
logger.error(`Error while processing group region:: ${err.stack}`);
return cb(err);
}
logger.info('Successfully processed Regions');
return cb();
})
}, function (err) {
if (err) {
return reject(err);
}
return resolve();
})
})
However, I am getting the below logs:
Successfully processed Zones
Successfully processed Regions
Successfully processed Regions
Successfully processed Zones
However, expected logs are:
Successfully processed Zones
Successfully processed Zones
Successfully processed Regions
Successfully processed Regions
As a result, sometimes zones are created twice but regions are getting created only 1.
Need to understand this async flow. Why it is not flowing sync flow.
Is there any other method which can be used?
>Solution :
The reason for the unexpected order is that the two promises are executed independently, and their internal iterations happen concurrently with a limit of 1
The provided code executes two asynchronous functions concurrently, resulting in logs being interleaved. To ensure a sequential flow, chain the promises using .then. Additionally, fix the callback calls by using callback(err) instead of cb(err) in the forEachLimit loop.
createGroupsForZones(var1, arr)
.then(() => createGroupsForRegions(var3, arr))
.then(() => {
console.log("All processing completed successfully.");
})
.catch((err) => {
console.error("Error during processing:", err);
});
there is a mistake in the provided code. The callback in the forEachLimit loop should be callback(err) instead of cb(err) since the callback function is named callback.
the updated code is
async.forEachLimit(arr, 1, function (eachZone, callback) {
abc(code, json, false, function (err) {
if (err) {
logger.error(`Error while processing group zone:: ${err.stack}`);
return callback(err); // Change cb(err) to callback(err)
}
logger.info('Successfully processed Zones');
return callback(); // Change cb() to callback()
})
}, function (err) {
if (err) {
return reject(err);
}
return resolve();
});
expected logs in the correct order:
Successfully processed Zones
Successfully processed Zones
Successfully processed Regions
Successfully processed Regions