I have this async function that should be logging the returned database record after it is inserted. Instead, node tries to log the record before the async await
function has returned the data from API.
fn: async function(inputs) {
let companyId = await tg.getCompanyIdByEmail(inputs.orderData.email)
let newCompany = {};
if (!companyId) {
newCompany = await tg.createCompany(inputs.orderData)
sails.log('new company id: ' + newCompany.id) // this line being called before await finishes above and throwing undefined error
}
return;
},
This is the async function tg.createCompany()
async createCompany(orderData) {
const companyType = orderData.business_name === "" ? 'consumer' : 'business';
const companyName = companyType === 'consumer' ? `${orderData.first_name} ${orderData.last_name}` : orderData.company_name;
let company = {
company_type: companyType,
name: companyName,
email: orderData.email
}
request({
method: 'POST',
url: `${this.baseUrl}/companies/`,
headers: this.headers,
json: company
}, (err, res, body) => {
if (err) throw new Error('request error: ' + err);
if (!body.company) throw new Error('API error: ' + body.message)
sails.log('tg company created', body.company) //this is logging AFTER other function errors out as undefined
return body.company;
})
}
How do I get the function to wait for the async function to return the data?