Robert
Robert

Reputation: 511

How to ensure my async function executes first before calling next function

My program is supposed to parse the results of a SQL query into a CSV file, then save to an FTP and S3 bucket. connectSQL is an async function that needs to execute completely before calling the writeToCSV function, but so far no matter what I've tried, writeToCSV executes before connectSQL, giving me an empty CSV file. How can I ensure that connectSQL executes before anything else?

function dataRefresh(){
	var resu = connectSQL();
	writeToCSV(resu);
}

async function connectSQL(){
	try {
		const sqlConfig = {
           // db connection config
		};
		
		const sqlQuery = "SELECT * FROM " + table;
		
    let pool = await sql.connect(sqlConfig);
    let result = await pool.request().query(sqlQuery);
    return result;
	} catch(err){
		throw err;
	}
}

function writeToCSV(event){
	// Parse to CSV
	var csv = parser({data: event.Records, fields: fields});
	// Write CSV to local directory
	fs.writeFile(fileName, csv, function(err){
		if (err){
			throw err;
		} else{
			console.log("Data saved locally");
		}
	});
}

I've tried reading as much as I can about asynchronous calls, and I feel I have a good understanding of what they're used for, but I've come up empty trying to solve my specific issue.

Upvotes: 2

Views: 982

Answers (2)

cbr
cbr

Reputation: 13632

Async functions return a Promise resolving to the return value of the function. You can either treat it like a promise and use .then(), or turn dataRefresh async as well and use await:

function dataRefresh(){
    connectSQL().then(result => writeToCSV(result));
    // or simply:
    // connectSQL().then(writeToCSV);
}

or

async function dataRefresh(){
    var result = await connectSQL();
    writeToCSV(result);
}

Upvotes: 4

grammar
grammar

Reputation: 871

Assuming that your code is running in an environment where async functions work, then I think all you need to do is add await in front of the call to connectSQL inside dataRefresh like so:

async function dataRefresh(){
    var resu = await connectSQL();
    writeToCSV(resu);
}

Upvotes: 1

Related Questions