Using Async inside another function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am using node.js and async with sails.js framework.
I am trying to create a function that perform some async DB operations on an array of data but I have problems figuring out a simple way to return the results of async to the parent function.
Here's my code:
convertProductfields: function (articlesFromAurelia){
async.each(articlesFromAurelia, function (post, cb) {
Categories.find({name: post.Categoria})
.then(function(category){
post.cat_id = category[0].cat_id;
cb();
})
.fail(function(error){
cb(error);
})
}, function(error){
if(error) return res.negotiate(error);
sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
return articlesFromAurelia;
});
sails.log.debug('articlesFromAureliaNotModified ' , articlesFromAurelia);
return articlesFromAurelia;
}
The problem of course is the execution order of the code. My function has already returned when the results of Async operations are available.... so, how to make it work? Thanks!!

Using Node 6.0, in built Promises can be used.
convertProductfields: function (articlesFromAurelia){
var allPromises = articlesFromAurelia
.map(post => new Promise((resolve, reject) => {
Categories.find({name: post.Categoria})
.then((category) => resolve(category))
.fail((error) => reject(error))
}));
return Promise.all(allPromises);
}
And to use the above function,
convertProductfields(articlesFromAurelia)
.then(() =>{
//handle success
}).catch(() => {
//handle error
})

Hope it helps you.
convertProductfields: function (articlesFromAurelia, callback){
async.each(articlesFromAurelia, function (post, cb) {
Categories.find({name: post.Categoria})
.then(function(category){
post.cat_id = category[0].cat_id;
cb();
})
.fail(function(error){
cb(error);
})
}, function(error){
if(error)
return callback(null); //incase of error, return null
sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
return callback(articlesFromAurelia); //return updated articles
});
}

Related

Promise not resolving before IF STATEMENT [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm trying to check the results of "checkWorkflow" but it seems to be running the "If" statement before checking, i think this because of my console output.
I feel like i'm doing something wrong with the promise, but i'm kinda at a lost at this point.
Console Output
Promise { pending } *When i console.log(doesWorkflowExists)
workflow already exists, please rename
error2
const createWorkflow = async (req, res) => {
try {
const doesWorkflowExists = checkWorkflow(req.name);
if (!doesWorkflowExists) {
console.log('do stuff')
}
else {
console.log('workflow already exists, please rename')
}
} catch (error) {
handleError(res, error);
console.log("error on create workflow");
}
};
vvvv checkWorkflow vvvv
const checkWorkflow = (name = '') => {
return new Promise((resolve, reject) => {
Workflow.findOne(
{
name,
},
(err, item) => {
if (err) {
console.log('error1')
return reject(buildErrObject(422, err.message));
}
if (item) {
console.log('error2')
return reject(buildErrObject(404, "WORKFLOW_ALREADY_EXISTS"));
}
resolve();
}
);
});
};
In your checkWorkflow function, you return a Promise. When you call checkWorkflow function like this :
const doesWorkflowExists = checkWorkflow(req.name);
doesWorkflowExists is a pending Promise. On the console, you can see that.
You need to "wait" until the Promise resolve the result or reject the error. Just add "await" keyword before the function call, like this:
const doesWorkflowExists = await checkWorkflow(req.name);
The rest seems to be fine, it should work :)

How to return to parent function in JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have the following function at the moment, and I want to return "aaa" to the parent function (getStream), this is the code I have atm:
module.exports.getStream = (figure) => {
plotly.plot(figure, imgOpts, function(err, stream) {
if (err) {
console.log(err);
return "error";
}
return "aaa";
});
};
Right now, however, it returns undefined. What's the best solution to solve that problem?
The problem is that getStream does not return anything (therefore its return value is undefined). You have to add return before plotly or just remove curly braces. Also you'll have to return a promise, because that third argument of plotly.plot method is a callback function (I guess).
module.exports.getStream = (figure) =>
new Promise((resolve, reject) => {
plotly.plot(figure, imgOpts, function(err, stream) {
if (err) {
console.log(err);
reject("error");
}
resolve("aaa");
});
})
and then somewhere in the app:
const foo = async () => {
try {
const result = await getStream(figure)
console.log(result) // 'aaa'
} catch (err) {
console.log(err) // 'error'
}
}

NodeJS array result empty when push [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am try to push data of my database into array but here I got little problem, when I try to console.log it's showing empty.
Here is my code :
var arrTodo =[];
conn.query(todoq,function(err, rows, fields) {
rows.forEach(function(detail){
arrTodo.push(detail.name);
});
});
console.log(arrTodo);
Anyone can help me put ?
Well as mentioned in comments, conn.query is asynchronous. so the callback you provide, is called at sometime later on while you've already console logged it.
You can use a promise to fix your problem:
function getQuery() {
return new Promise(function (resolve, reject) {
conn.query(todoq,function(err, rows, fields) {
var arrTodo = [];
if (err) {
return reject(err);
}
rows.forEach(function(detail){
arrTodo.push(detail.name);
});
return resolve(arrTodo);
});
});
}
getQuery().then(arrTodo => console.log(arrTodo)).catch(err => console.error(err));
Also, you could improve your code a bit using arr.map method, like this:
function getQuery() {
return new Promise(function (resolve, reject) {
conn.query(todoq,function(err, rows, fields) {
if (err) {
return reject(err);
}
let arrTodo = rows.map(function(detail){
return detail.name;
});
return resolve(arrTodo);
});
});
}
getQuery().then(arrTodo => console.log(arrTodo)).catch(err => console.error(err));
With promises, you can also use async-await:
(
async function () {
let arrTodo = await getQuery();
console.log(arrTodo);
}
)()
Try this.
var arrTodo =[];
conn.query(todoq,function(err, rows, fields) {
rows.forEach(function(detail){
arrTodo.push(detail.name);
});
console.log(arrTodo);
});

How to wait until stream async is executed in nodejs [duplicate]

This question already has answers here:
How to use ES8 async/await with streams?
(7 answers)
Closed 4 years ago.
Hi I have async nodejs function where I am using stream concept. I want once stream is completed then I want to return from this function.
const removeMapping = async function (query) {
let stream = query.foreach();
stream.on('data', function (record) {
client.delete(record);
})
stream.on('error', function (error) {
})
stream.on('end', function () {
console.log("completed");
})
};
I am calling this function like this but after execution of this line, stream async code after this.
await mapping.deleteMapping(cookie);
Does anyone know how to handle this ?
Your function doesn't need to be async as you are not calling await within the function.
What you can do is return a new promise:
const removeMapping = function (query) {
return new Promise((resolve, reject) => {
let stream = query.foreach();
stream.on('data', function (record) {
client.delete(record);
})
stream.on('error', function (error) {
reject(error);
})
stream.on('end', function () {
resolve("completed");
})
})
};
You can then resolve or reject depending on what comes back from your stream.

Inside async function, returning value from a callback function returns Promise(undefined) [duplicate]

This question already has answers here:
How to turn this callback into a promise using async/await?
(2 answers)
How do I convert an existing callback API to promises?
(24 answers)
Closed 5 years ago.
I'm new to asynchronous programming,
I'm facing issue similar to this question, in this question suggested approach uses callbacks but I'm trying to do it using Promises and async-await functions. I get undefined in the console. Here's my example. what am I missing?
//Defining the function
async query( sql, args ) {
const rows = this.connection.query( sql, args, async( err, rows ) =>
{
if ( err )
throw new Error(err);
return rows;
} );
}
//calling the function here
db.query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));
make your query function return a Promise
function query(sql, args) {
return new Promise(function (resolve , reject) {
this.connection.query(sql, args, (err, rows) => {
if (err)
reject(err);
else
resolve(rows)
});
});
}
//calling the function here
query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));

Categories