Asynchronicity - Legitimization , and Some Words on Theory

In Node.js asynchronicity is a fundamental issue. We have seen that already. It gives us certain coding issues. Take a look at

client.connect(
    url, { useNewUrlParser: true, useUnifiedTopology: true}, function (err, dbh) {
        if (err) {
            console.error(err);
            return;
        }
                                                    // callback for connect
        let saltRounds = 10;
        let myPlaintextPassword = 'test';
        bcrypt.hash(myPlaintextPassword, saltRounds, function (bcerr, hash) {
            if (bcerr)
                throw bcerr;
                                                    // calback for bcrypt under connect
            let data = { userid: "nml", email: "nml@acm.org", pwd: hash }
            dbh.db().collection("todoer").insertOne(data, function (dberr, collection) {
                if (dberr) {
                    throw dberr;
                }
                                                    // callback for insert under bcrypt under connect
                dbh.close();
            });
    });

We see three levels of callbacks. It is by no means rare. It is by no means readable. It often goes beyond three layers. In order to deal with that TC39, the technical group behind the JS language, has invented promises. We shall look at that in a bit, I promise.

You may say that we introduce asynchronicity in order to get the benefits of parallel processing, then we have to do promises to fix the consequences with respect to chaotic code. You do something to make it better, then you have to do yet more to make it tolerable. What happened to KISS?

Let us first look at the JavaScript concept of Promises here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise.

Then we shall take a look at async/await here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function.