0

Ok, so I know how to program in C# fairly well and I have started programming in JS recently (node js). To be honest I was in a bot of shock from async calls.

Let's say I have this code in C#:

var t_1 = SomeAsyncTask();
var t_2 = SomeOtherAsyncTask();
Task.WaitAll(t_1, t_2);
var res_1 = t_1.Result;
var res_2 = t_2.Result;

Is there a JS equivalent of this? So far I have managed this:

In User.js:
var express = require("express");
var router = express.Router();
var sqlDo = require("../../js_help/DatabasReq/sqlDo.js");
router.get("/", async function(req, res){
    var json = sqlDo.ExecCommand("select * from Users");
    res.send(json); //json.recordset
});
module.exports = router;

In sqlDo.js:
module.exports = {
    ExecCommand: function(command){
        // sql and config are defined before.
        sql.connect(config, function () {
            var request = new sql.Request();
            request.query(command, function (err, recordset) {
                if (err) console.log(err)
                console.log(recordset.recordset);
                return recordset;
            });
        });
    }
};

My problem is that this code is running async. I have tried putting await to different places but nothing worked. So when I start my server it returns nothing. I can tell that it is completing a call because I let it read results into console.

Thanks for any help!

Btw: I have tried googling/stackoverlow-ing,.. But I was not able to find anything that would look like C# equivalent. Is it even possible to write it like in c#? Again thanks for every answer...

6
  • 1
    The nearest to Task.WaitAll(t1, t2) would be Promise.all([p1, p2]) as async/await in JS is more or less syntactic sugar for promises. Commented Sep 19, 2020 at 22:19
  • 1
    It wouldn't be too much of an exaggeration to say that all "classic" languages (C, C++, Java and C#) are essentially "blocking", and, in contrast, Javascript was always "asynchronous". One wait to achieve an "await" in JS is to use Promises. "Async" was bolted on to later versions of .Net/C#; "Promises" to later versions of JS. Commented Sep 19, 2020 at 22:19
  • Ok, so how can I join to the database and then return responce with data from database. And I want to have it in some function, so I can reuse it? Commented Sep 19, 2020 at 22:20
  • Q: Ok, so how can I join to the database...? A: Look at the link I cited. Have your callback return a promise; have your caller(s) wait on the promise. Easy peasy ;) Commented Sep 19, 2020 at 22:24
  • To stay within your above example: ExecCommand has to be an async function (ie returning a promise), and in your requesthandler you have to await ExecCommand(...) before returning the result. Basically the same, as you would do it with Tasks in C# Commented Sep 19, 2020 at 22:24

1 Answer 1

1

To make your ExecCommand function async, you have to make it return a Promise. Read about Promises for instance here

module.exports = {

  ExecCommand: function(command){
    return new Promise((resolve, reject) => {  //return a Promise from the function
      sql.connect(config, function () {
        var request = new sql.Request();
        request.query(command, function (err, recordset) {
          if (err) {
            reject(err);  //if there is an error, reject the Promise
          } else {
            resolve(recordset);  //if no error, resolve the Promise with the result
          }
        });
      });
    });
  }
};

Depending on your SQL library, it may also support promises already, instead of callbacks

module.exports = {

  ExecCommand: function(command) {
     return sql.connect(config)
       .then(() => {
          return new sql.Request().query(command);
       })
  }
};

or with async/await

module.exports = {

  ExecCommand: async function(command) {
    await sql.connect(config);
    return await new sql.Request().query(command);         
  }
};

Then you can call this function in the requesthandler either like this

router.get("/", async function(req, res){
  try {
    var json = await sqlDo.ExecCommand("select * from Users");
    res.send(json); 
  catch (err) {
    console.log(err);
    res.sendStatus(500);
  }
});

or like this

router.get("/", function(req, res){
  sqlDo.ExecCommand("select * from Users")
    .then(json => { //the promise resolved
      res.send(json);
    })
    .catch(err => { //the promise rejected
      res.sendStatus(500); 
      console.log(err); 
    });
});

I prefer the second variant. But that may be just my personal opinion ...

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Thanks, I actually understood what is going on from your examples. Approve and upvote. Hope you have a grate day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.