Reputation: 75
I'm trying to assign a value to the variable myleadId
depending on leadId.length
.
The goal is that myleadId
will have a value after this step to continue with the next step. The problem is that myleadId
is undefined
when leadId.length <= 0
(else condition).
app.post('/sendMessage2agent', async (req, res) => {
getEnterpriseIDbyContact(req.body.recipient, knex).then((enterpriseId) => {
getLeadIDbyContact(req.body.sender, knex).then((leadId) => {
var myleadId;
if (leadId.length > 0) {
myleadId = leadId; //works great!
} else {
getChannelIdByName(req.body.channel, knex).then((channelId) => {
return createLeadOnEnterprise(req.body.sender, enterpriseId, channelId, knex).then((newleadId) => {
console.log('newleadId: ' + newleadId); //newleadId is 5
myleadId = [{'id': newleadId}]; //doesn't work :(
return;
});
});
}
console.log('myleadId: ' + JSON.stringify(myleadId)); // myleadId is undefined when leadId.length>0 is false. I expect myleadId=[{'id': 5}]
});
res.json(req.body);
});
});
Upvotes: 3
Views: 184
Reputation: 2314
The problem is that you're not awaiting your promises. That way they will finish at a different time than your console.log
. What you should also see is that the message myleadId: ...
appears before newleadId: ...
in the console. This is because promises execute asynchronously. So they let other code continue while they are executing. To ensure that a promise is awaited before continuing with the main function you should use await
. With that you can also remove the .then
callbacks to improve readability.
app.post('/sendMessage2agent', async (req, res) => {
const enterpriseId = await getEnterpriseIDbyContact(req.body.recipient, knex);
const leadId = await getLeadIDbyContact(req.body.sender, knex);
let myleadId;
if (leadId.length > 0) {
myleadId = leadId;
} else {
const channelId = await getChannelIdByName(req.body.channel, knex);
const newleadId = await createLeadOnEnterprise(req.body.sender, enterpriseId, channelId, knex);
console.log('newleadId: ' + newleadId);
myleadId = [{'id': newleadId}];
}
console.log('myleadId: ' + JSON.stringify(myleadId));
res.json(req.body);
});
Upvotes: 2