As far as I have seen then async/await, callbacks and promises are and can only be used to achieve asynchronous programming. Correct?
So my questions are:
1) Is it correct that the former three is used for asynchronous programming only?
2) If yes, then which of them is the best and why?
3) If no, then how they differ?
I was trying mssql module of node.js and I tried different ways:
Using Async/Await:
app.get('/app/users', async (res, req) => {
try {
const config=
{
server: 'localhost',
database: 'HimHer',
user: 'sa',
password: 'Jessejames01',
port: 1433
}
let pool = await sql.connect(config)
let result1 = await pool.request().query('select top 1 * from dbo.Users');
console.dir(result1);
res.send(JSON.stringify(result1));
} catch (err) {
// ... error checks
}
})
Using Promises:
sql.connect(config).then(pool => {
// Query
return pool.request().query('select * from dbo.Users')
}).then(result => {
console.dir(result);
res.send(JSON.stringify(result));
}).catch(err => {
console.log('Exception:+ '+err);
sql.close();
})
Using Callbacks:
new mssql.connect(configuration, error =>
{
new mssql.request().query('Select * from Users', (err, dataset) =>
{
if(err)
{
console.log(err);
res.send(err);
return;
}
else
{
console.dir(dataset);
res.send(JSON.stringify(dataset));
return;
}
});
});
mssql.close();
Since all are achieving the same.
GOTO
, recursion, andWHILE
loops all can be used to achieve Turing-completeness then why don't we stick to one?"