I am being ask this question often; therefore, I am posting the answer here.
Commonly there are those who wish to do a process that normally is asynchronously, such as performing AJAX operations in a synchronous fashion. There are a few ways to do this.
If you are coding in JS for NodeJS, then you can use the package async-waterfall, example:
function readFile(callback) { fs.readFile('your_file.json', function (error, file) { if (error) { callback(error); } else { callback(null, file); } }); } ... function processFile(file, callback){ // Some code here } ... async.waterfall([ readFile, processFile ], function (error) { if (error) { // handle error made in readFile or processFile method } });
Else, you can use promise chains which is part of Javascript, example:
new Promise(function(resolve, reject) { try{ resolve(readfile()); }catch(e){ reject("error message"); } }).then(function(result) { return processFile(result) });
Or, you can use async/await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
© 2018, Alejandro G. Carlstein Ramos Mejia. All rights reserved.