I am using async waterfall like this
const profileRichness = () => {
async.waterfall([
getTargetUsers,
filterUser,
], (err) => {
if (err) errorlogger(uuid(), err, "email", "abc", "acc", "acd");
else console.log('Done');
});
}
Fn that I am calling
const getTargetUsers = (callback,condition) => {
user.getUsers(condition, (err, result) => {
if (err)
callback(err);
else {
if (result.length)
callback(null, result);
else
callback('No user found');
}
});
}
const filterUser = (users, callback) => {
users = users.filter(user => {
if (!user.age || user.profile < 80) return user;
else return false;
}).filter(user => user);
callback(null,users);
}
Problem is whatever I am trying to pass in first function of waterfall it returns error that "callback is not a function" what is exactly going on
Related
I'm making a request to my database, I set the functions as asynchronous and to wait, but it still returns me undefined or Promise { pending }
how do I just return it when I have the result?
export const getGerente = async (req, res) => {
var query = "SELECT * FROM inventory;"
const r = await select(query)
console.log(r)
return res.json({message:"teste"})
}
export async function select(query) {
var teste = await client.connect(() =>{
client
.query(query)
.then((resultado) => {
console.log('sucess!!');
return resultado.rows
/*
const rows=resultado.rows
rows.map(x =>{
console.log(x.name)
})*/
})
.catch((erro) => {
console.log("erro: " + erro.message);
})
.then((teste) => {
console.log('Finished execution, exiting now');
process.exit();
});
})
}
result: Promise { pending }
I'm calling her for a request
Your select function is not awaiting the client.connect properly.
Try this for select function -
export async function select(query) {
const promisifiedRows = new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err); // err in connecting
} else {
console.log('Connected!');
client.query(query, (err, rows) => {
if (err) {
reject(err); // err while exceuting the query
} else {
resolve(rows);
}
});
}
});
});
const rows = await promisifiedRows();
return rows;
}
Hope everyone of you are doing well. I am stuck in a bit of problem. Any help will be highly appreciated.
I am using ldapJS and I want to call another promise from searchEntry method of LDAPJS. When i write the code same as below. it throws an error
exports.getADUsers = async (reqst, resp, next) => {
let flag = false;
var finalList = [];
let adConnStatus = await ConnectAD()
.then().catch((errConnStatus) => {
console.log("Error in connection with Active directory " + errConnStatus);
});
if (adConnStatus.status == 0) {
let client = adConnStatus.client;
const opts = {
filter: '(ObjectClass=*)',
scope: 'sub',
attributes: ['cn', 'sid', "objectSid"]
};
client.search('dc=domain,dc=com', opts, (err, res) => {
if (err) {
console.log("Error: " + err);
} else {
res.on('searchEntry', (entry) => {
finalList = await searchEntry(entry);
});
res.on('searchReference', (referral) => {
console.log('referral: ' + referral.uris.join());
});
res.on('error', (err) => {
console.error('error: ' + err.message);
});
res.on('end', (result) => {
resp.send(finalList);
console.log(result);
});
}
});
}
}
Error:
finalList = await searchEntry(entry);
^^^^^
SyntaxError: await is only valid in async function
Please help! how to call another promise from one promise. Though the method is async why it shows this message? what am i doing wrong?
EDIT
After adding the keyword async as suggested by #Punth. Also modifying a bit of the code. my new code is as follows.
exports.getADUsers = async (reqst, resp, next) => {
let adConnStatus = await ConnectAD()
.then().catch((errConnStatus) => {
console.log("Error in connection with Active directory " + errConnStatus);
});
if (adConnStatus.status == 0) {
var adUsersList = [];
let client = adConnStatus.client;
const opts = {
filter: '(ObjectClass=*)',
scope: 'sub',
attributes: ['cn', 'sid', "objectSid"]
};
client.search('dc=domain,dc=com', opts, (err, res) => {
if (err) {
console.log("Error: " + err);
} else {
res.on('searchEntry', async (entry) => {
var raw = entry.raw;
if (raw.objectSid != "undefined" && raw.objectSid != null && entry.object.cn != null && entry.object.cn != "undefined") {
let userData = {
"Name": entry.object.cn,
"SSID": sidBufferToString(raw.objectSid)
}
var lmn = await ConnectAndGetUsersList(userData.SSID);
userData["XYZ"] = lmn.xyz;
userData["ABC"] = lmn.abc;
adUsersList.push(userData);
}
});
res.on('searchReference', (referral) => {
console.log('referral: ' + referral.uris.join());
});
res.on('error', (err) => {
console.error('error: ' + err.message);
});
res.on('end', (result) => {
console.log(result);
resp.send(adUsersList);
});
}
});
}
}
By running the above code it doesn't shows me anything. res.on('end' ....) is called prior to res.on("searchEntry"....) Therefore the array of adUsersList is null.
Now my question is how to resp.send the final arraylist???
Update this line as follows, to invoke promises using async/await syntax inside a callback you need to make it async
res.on('searchEntry', async (entry) => {
finalList = await searchEntry(entry);
});
I need to call two async functions sequentially inside a new function. Both functions use callbacks to perform asynchronous operations.
When I just call my functions one by one I am faced with the problem that, as I understand it, they are called synchronously, and the second function does not wait for the first to execute
How can I wrap them to be performed sequentially?
Code that I have:
let firstFunction = (data, callback) => {
DBCallingFirst
.asyncMethodFirst(resultObj, (err, result) => {
if (err) return callback(err);
// Some code
});
}
let secondFunction = (data, callback) => {
DBCallingSecond
.asyncMethodSecond(resultObj, (err, result) => {
if (err) return callback(err);
// Some code
});
}
let newFunction = (data, callback) => {
firstFunction(data, callback);
secondFunction(data, callback);
}
Thanks for your attention!
If you are able to use promises, or async/await, you can make this a lot cleaner. As it is, you can just do the second db operation in the callback from the first one - so that guarantees the first one completes before calling the second
let firstFunction = async (data, callback) => {
DBCallingFirst
.asyncMethodFirst(resultObj, (err, result) => {
if (err) return callback(err);
DBCallingSecond
.asyncMethodSecond(resultObj, (err, result) => {
if (err) return callback(err);
// Some code
});
});
}
EDIT: With promises, you could structure it like this:
let firstFunction = (data) => {
return new Promise(() => {
DBCallingFirst
.asyncMethodFirst(data, (err, result) => {
if (err) {
return Promise.reject();
}
return Promise.resolve(result);
});
});
}
let secondFunction = (data) => {
return new Promise(() => {
DBCallingSecond
.asyncMethodSecond(data, (err, result) => {
if (err) {
return Promise.reject();
}
return Promise.resolve(result);
});
});
}
let newFunction = (data, callback) => {
firstFunction(data).then((result1) => {
secondFunction(data).then(result2) {
}).catch(err2) {
console.error(err2);
});
}.catch((err1) => {
console.error(err1);
});
}
Return Promise from both the functions and await them like this
const firstFunction = (data) => {
return new Promise((resolve, reject) => {
DBCallingFirst.asyncMethodFirst(data, (err, result) => {
if(err) reject(err);
resolve(result);
})
})
}
const secondFunction = (data) => {
return new Promise((resolve, reject) => {
DBCallingSecond.asyncMethodSecond(data, (err, result) => {
if(err) reject(err);
resolve(result);
})
})
}
Now you can call both of them sequentially using await
const newFunction = async (data) => { // note the async part in function definition
try {
const result1 = await firstFunction(data);
const result2 = await secondFunction(data); // this will be executed only after firstFunction resolves/rejects;
} catch (err) {
console.log('Error from the function', error) // promise rejection will be caught here
}
}
I want to create a function which can be utilised in 3 ways for creating npm dependency
Promise way
callback way
async/await way
For Example
1) async/await
var mongoose = require('mongoose');
async function Connection() {
try {
await mongoose.connect('mongourl');
} catch (err) {
console.error("Connection error --->", err);
}
}
Connection();
2) Callback Style
var mongoose = require('mongoose');
mongoose.connect('mongourl', function (err) {
if (err) console.error("Connection error --->", err);
});
3) Promise Style
var mongoose = require('mongoose');
mongoose.connect('mongourl').then(() => {
}).catch(err => console.error("Connection error --->", err));
Did u absorve that mongoose.connect is same name for all types
You can try with:
const connect = (name, callback) => {
try {
const result = /* generate result */
if (callback) {
callback(null, result);
} else {
return Promise.resolve(result);
}
} catch (e) {
if (callback) {
callback(e);
} else {
return Promise.reject(e);
}
}
}
And quick usage example:
connect('John')
.then(result => { /* ... */ })
.catch(error => { /* ... */ });
connect('John', (error, result) => { /* ... */ });
async function foo() {
try {
const result = await connect('John');
} catch (error) { /* ... */ }
}
Here is an example, it's similar to #hsz, but I've put the handling for the inner callback.
If your pass a callback it does this in a callback way, if not it returns a Promise instead.
If you run the snippet you can see it in action.
I've basically created a simple setTimeout function that randomly fails, to show how error handling is also done. So to see the full effect try running the snippet a few times.
function doInner(name, callback) {
setTimeout(() => {
if (Math.random() < 0.5)
callback(null, "Did " + name);
else callback(new Error("Oops in " + name));
}, 1000);
}
function doSomething(name, callback) {
if (callback) {
doInner(name, (err, result) => {
if (callback) callback(err, result);
});
} else return new Promise((resolve, reject) => {
doInner(name, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
//now lets test both ways
doSomething("test callback", (err, result) => {
if (err) console.error(err);
else console.log(result);
});
(async function () {
try {
const result = await doSomething("Promise");
console.log(result);
} catch(e) {
console.error(e);
}
}());
I would like to call use async waterfall function within a async series function. looks like parallel functions are executed but final callback function of async series does not seem to be executed. I get the results of the instances of the function which is called with different arguments in series function but cannot have the line executed for some reason.
➜ lib git:(jumpstart-compare) ✗ node aws-ecs.compare.js
Data 1f701a9754eb22ce8f0dcdb4c1b0b366a51ade9a
Data 4cc27bcc2a8482478ac2e5c0cf3ac1babe153374
var AWS = require('aws-sdk');
const async = require('async')
const _ = require('lodash');
AWS.config.update({
region: 'us-east-1'
});
const ecs = new AWS.ECS();
getClusterSha = (clustername,app,callback) => {
const ListServices = (callback) => {
let params = {
cluster: clustername
}
//console.log('list tasks executed')
ecs.listServices(params, (err, data) => {
if (err) {
callback(err)
} else {
let dataObj = {
data: data,
cluster: clustername
}
callback(null,dataObj)
}
})
}
const getService = (arg1, callback) => {
let appname = app
arg1.cluster
let finaldata = arg1.data.serviceArns.filter((elem)=>{
if(elem.indexOf(appname) != -1){
return elem
}
});
//console.log('finaldata: ',finaldata)
if(finaldata.length > 0){
callback(null,finaldata.toString().split('/')[1])
}else{
callback('No app with name: '+appname+' found!')
}
}
const describeService = (arg2, callback) => {
let params = {
services: [arg2],
cluster: clustername
}
ecs.describeServices(params, (err, data) => {
if (err) {
callback(err)
} else {
// console.log(data)
callback(null,data.services[0].taskDefinition.split('/')[1])
}
})
}
const describeTaskDef = (arg3, callback) => {
let params = {
taskDefinition: arg3
}
ecs.describeTaskDefinition(params, (err, data) => {
if (err) {
callback(err)
} else {
//console.log(data.taskDefinition.containerDefinitions[0].image.split('/')[1].split(':')[1])
finaldata = data.taskDefinition.containerDefinitions[0]
.image.split('/')[1]
.split(':')[1]
callback(null,finaldata)
}
})
}
// const githubCall = (arg4,callback) => {
// console.log('https://github.com/Jumpstart-Auto'+'/'+app+'/commit/'+arg4)
// callback(null,'https://github.com/Jumpstart-Auto'+'/'+app+'/commit/'+arg4)
// }
async.waterfall([
ListServices,
getService,
describeService,
describeTaskDef,
], (err, data) => {
if (err) {
console.log('Error', err)
callback(err)
} else {
console.log('Data', data)
callback(null,data)
}
})
}
compareSha = (clustername1,clustername2,app) => {
async.series([
getClusterSha(clustername1,app,(data)=>{return data}),
getClusterSha(clustername2,app,(data)=>{return data})
], (err,result)=>{
console.log(err,result)
})
}
compareSha('dev','staging','jamobot',function(err,data){
console.log(data)
})
//module.exports = getShaCluster
changing async.series to following fixed the problem.
async.waterfall([
ListServices,
getService,
describeService,
describeTaskDef,
], (err, data) => {
if (err) {
console.log('Error', err)
callback(err)
} else {
console.log('Data', data)
callback(null,data)
}
})
}
compareSha = (clustername1,clustername2,app,cb) => {
async.series([
function(callback){
getClusterSha(clustername1,app,callback)
},
function(callback){
getClusterSha(clustername2,app,callback)
},
], (err,result)=>{
if(err){
cb(err)
}else{
cb(null,result)
}
})