Async method, Iterator should be happend when update is happend - node.js

I have an array which is being iterated using Asynch.forEachSeries. Inside the iterator I find the model and updated. I need to iterate the second item after update is happened. Find the code below.
async.eachOfSeries(stockUpdate, function (valueSU, keySU, callbackSU) {
ProductVariations.findOne({id:valueSU.id}).exec(function (ePV,dPV){
dPV.available_stock = parseInt(dPV.available_stock) - Qty;
dPV.save(function (errDPV) {
callbackSU(); // HERE ONCE, NEXT ITERATOR SHOULD BE CALLED
});
});
}, function (err) {
if (err) callback(err.message);
});

I think you should wrap "ProductVariations..." in promise. And wait, until it resolves. And then call next iterator.
This code must solve you task
let promiseProductVariations = function (valueSU, keySU) {
return new Promise(function (resolve, reject) {
ProductVariations.findOne({id:valueSU.id}).exec(function (ePV,dPV){
dPV.available_stock = parseInt(dPV.available_stock) - Qty;
dPV.save(function (errDPV) {
if(errDPV){
reject(errDPV);
}else{
resolve(); // HERE ONCE, NEXT ITERATOR SHOULD BE CALLED
}
});
});
})};
async.eachOfSeries(stockUpdate, function (valueSU, keySU, callbackSU) {
promiseProductVariations(valueSU, keySU)
.then(function () {
callbackSU();
})
.catch(function (error) {
if(error)
console.log(error);
//do thomething with error
});
}, function (err) {
if (err) callback(err.message);
});

Related

Can't work out promises to return values - NodeJS

After searching through countless posts I don't understand why I'm still getting a Promise pending after my awaits. The code below should explain it but I'm trying to pull a MongoDB query of the max value of a column/schema. The console.log within the function is giving me the correct timestamp but I'm trying to pass that out of the inner scope and function to another function.
This is pure NodeJS with only MongoDB imported. Can this be done without any external packages?
export async function getMaxDate() {
var time = MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
if (err)
throw err;
var dbo = db.db(getDB);
dbo.collection(getColl)
.find()
.limit(1)
.sort({ 'timestamp': -1 })
.toArray(function (err, result) {
if (err)
throw err;
time = result[0].time; // THIS IS GIVING THE CORRECT VALUE
console.log(time)
db.close();
});
});
return time
}
export async function getMax() {
var block = await getMaxDate();
return block
}
var t = getMax();
console.log(t); // THIS IS GIVE ME A PROMISE PENDING
getMax() returns a promise, you have to wait for it.
var t = await getMax()
Also getMaxDate uses an async callback that you want to promisify:
export async function getMaxDate() {
return new Promise((resolve,reject) => {
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
if (err)
return reject(err);
var dbo = db.db(getDB);
dbo.collection(getColl)
.find()
.limit(1)
.sort({ 'timestamp': -1 })
.toArray(function (err, result) {
if(err)
reject(err);
else {
let time = result[0].time; // THIS IS GIVING THE CORRECT VALUE
console.log(time)
db.close();
resolve(time);
}
});
})
});
}
For reference, A is the same thing as B here:
async function A(x) {
if(x)
throw new Error('foo');
else
return 'bar';
}
function B(x) {
return new Promise((resolve,reject)=>{
if(x)
reject(new Error('foo'));
else
resolve('bar');
});
}
Promises came first, then async/await notation was introduced to make common Promise coding practices easier
You can use A and B interchangeably:
async function example1() {
try {
await A(1);
await B(0);
}
catch(err) {
console.log('got error from A');
}
}
async function example2() {
return A(0).then(()=>B(1)).catch((err)=>{
console.log('got error from B');
})
}

How to get to be return and print in outside function using node js

I tried one simple function in node js and pass data to one file on to another file.but its throwing undefined.how to solve it in node js
fun.js
function Get_Value()
{
client.get('products', function(err,results) {
return results
})
console.log(results)
}
I tried to print value in outside the function but its print undefined how to print result in out side function
async function Get_Value() {
let results = await new Promise(function(resolve) {
client.get("products", function(err, results) {
resolve(results);
});
});
console.log(results);
}
This is very easy using async/await features provided by ES7.
async function Get_Value()
{
const results = await new Promise((resolve, reject) => {
client.get('products', function(err,results) {
resolve(results);
})
});
console.log(results);
}
Define your Get_Value to take a callback function. You then pass a callback when you're invoking Get_Value:
function Get_Value(callback) {
client.get('products', function(err,results) {
if (err) return callback(err)
callback(null, results);
})
}
function mycallback(err, data) {
if (err) {
// handle error
console.error(err)
} else {
console.log(data);
}
}
Get_Value(mycallback)

Resolve not working in loop Node.js

Hi I have a problem running a loop and getting the return data using Promises.
I have a getStudentMarks method for getting students marks from the database in subject wise.
getStudentMarks: function(studentId, studentStandard) {
console.log("getStudentMarks invoked...");
return new Promise(function(resolve, reject) {
r.table('student_subjects').filter({
"studentId": studentId,
"studentStandard": studentStandard
}).pluck("subjectId", "subjectName").run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result) {
if (err) {
throw err
} else {
console.log(result.length);
if (result.length > 0) {
studentSubjectArray = result;
var studentMarksSubjectWiseArray = [];
studentSubjectArray.forEach(function(elementPhoto) {
r.table('student_marks').filter({
"studentId": studentId,
"subjectId": studentSubjectArray.subjectId
}).run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result_marks) {
var studnetMarksDataObject = {
subjectId: studentSubjectArray.subjectId,
subjectName: studentSubjectArray.subjectName,
marks: result.marks
};
studentMarksSubjectWiseArray.push(studnetMarksDataObject);
});
}
});
});
resolve(studentMarksSubjectWiseArray);
}
}
});
}
});
});
}
I'm invoking the method by,
app.post('/getStudentMarks', function(req, reqs) {
ubm.getStudentMarks(req.body.studentId, req.body.studentStandard)
.then((data) => {
console.log('return data: ' + data);
})
.catch((err) => {
console.log(err);
});
});
When I run the code its working absolutely fine there is no error. I get all the student marks object in the studentMarksSubjectWiseArray array. But the problem is even before the studentSubjectArray loops gets completed, the resolve is getting executed and I'm getting a blank array as return. How do I solve the problem. I understand that I'm not doing the Promises right. I'm new to Promises so I'm not being able to figure out the right way.
That happens because inside your studentSubjectArray.forEach statement you perform set of asynchronous operations r.table(...).filter(...).run() and you push their result into the array. However, those actions finish after you perform the resolve(), so the studentMarksSubjectWiseArray is still empty. In this case you would have to use Promise.all() method.
let promisesArray = [];
studentSubjectArray.forEach((elementPhoto) => {
let singlePromise = new Promise((resolve, reject) => {
// here perform asynchronous operation and do the resolve with single result like r.table(...).filter(...).run()
// in the end you would perform resolve(studentMarksDataObject)
r.table('student_marks').filter({
"studentId": studentId,
"subjectId": studentSubjectArray.subjectId
}).run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result_marks) {
var studnetMarksDataObject = {
subjectId: studentSubjectArray.subjectId,
subjectName: studentSubjectArray.subjectName,
marks: result.marks
};
resolve(studnetMarksDataObject);
});
}
});
});
promisesArray.push(singlePromise)
});
Promise.all(promisesArray).then((result) => {
// here the result would be an array of results from previously performed set of asynchronous operations
});

How to chain promise in array

I need help with ES6 Promises chaining in array processing.
How to process/define each item of array which goes into Promise.all method, when there is other async method inside resolve?
Here is simplified example:
function getData(data, callback) {
let groupPromises = data.map(row => {
var coordinates = getCoordinates(row);
return Promise.resolve({
"place": getPlaces(coordinates), //how to invoke this method
"data": row
};
});
Promise.all(groupPromises)
.then(groups => callback(groups))
.catch(err => console.log(err));
}
}
function getPlaces(coordinates) {
return new Promise(function(resolve, reject) {
if(coordinates == null) {
reject();
}
parameters = {
location: [coordinates.latitude, coordinates.longitude],
rankby: "distance",
};
googlePlaces.searchPlace(parameters, function (error, response) {
if (error) {
reject(error);
};
resolve(response);
});
}
}
You can do it like this where you add a .then() handler to your first promise that gets the place and then when that's available returns the object you want. The resolved results of your Promise.all() will then be the array of objects you want:
function getData(data, callback) {
let groupPromises = data.map(row => {
var coordinates = getCoordinates(row);
// add .then() handler here to convert the place result
// into the object you want it in
return getPlaces(coordinates).then(place => {
return {place: place, data: row};
});
});
return Promise.all(groupPromises)
.then(groups => callback(groups))
.catch(err => {
console.log(err);
throw err;
});
}
}
function getPlaces(coordinates) {
return new Promise(function(resolve, reject) {
if(coordinates == null) {
reject();
}
parameters = {
location: [coordinates.latitude, coordinates.longitude],
rankby: "distance",
};
googlePlaces.searchPlace(parameters, function (error, response) {
if (error) {
reject(error);
};
resolve(response);
});
}
}
FYI, since you're converting over to promises, why not just return the promise from getData() and not use a callback there at all? Your current code has no way of communicating back an error from getData() which is something that comes largely for free with promises.
In fact with pure promises, getData() could be simplified to this:
function getData(data, callback) {
return Promise.all(data.map(row => {
return getPlaces(getCoordinates(row)).then(function(place) {
return {place: place, data: row};
});
}));
}

Promise.all().then() - then() executes before all() completed

In a gulp task I have the following code that creates an array of gitAction promises that get executed within a Promise.all() statement. Afterwards, I'm calling a further statement in a then(). But the then() is being called before the git pulls in the all() have terminated. Any clues please?
var git = require('gulp-git');
var gitActionPromise = function(repo, url) {
console.log('git action '+repo);
var pathToRepo = './repos/'+repo;
if (fs.lstatSync(pathToRepo).isDirectory()) {
return new Promise((resolve, reject) => {
git.pull('origin', 'master', {cwd: pathToRepo}, function (err) {
console.log(repo + " pull done!");
if (err) {
console.log('error');
reject(err);
} else {
console.log('ok');
resolve();
}
})
})
} else {
return new Promise((resolve, reject) => {
git.clone(url, {cwd: pathToRepo}, function (err) {
console.log(repo + " clone done!");
if (err) {
console.log('error');
reject(err);
} else {
console.log('ok');
resolve();
}
})
})
}
};
var repos = package.repos || {};
var promises = Object.keys(repos).map(function(repo) {
return gitActionPromise(repo, repos[repo]);
});
Promise.all(promises).then(
console.log('something else') <= this line was causing my issue
); needed to be enclosed in function
You have to pass a function to then:
Promise.all(promises).then(function() {
console.log('something else');
});
The code you have simply logs "something else" right away.

Resources