简体   繁体   中英

what is the db argument's value or usage for this javascript es6 fat arrow function?

initializeDb( db => {

    // internal middleware
    app.use(middleware({ config, db }));

    // api router
    app.use('/api', api({ config, db }));

    app.server.listen(process.env.PORT || config.port, () => {
        console.log(`Started on port ${app.server.address().port}`);
    });
});

https://github.com/developit/express-es6-rest-api/blob/master/src/index.js#L27

Above situation, the db seems pop out of nowhere, to see the context, please click on the link direct to the source code.

I simulated the same way here ( https://codepen.io/adamchenwei/pen/vWWmXa ) the db shouldn't even be accessible. What exactly the db does then in that specific boilerplate?

db is the argument of the call back function of initializeDb

The code actually looks like this

'use strict';

initializeDb(function (db) {

    // internal middleware
    app.use(middleware({ config: config, db: db }));

    // api router
    app.use('/api', api({ config: config, db: db }));

    app.server.listen(process.env.PORT || config.port, function () {
        console.log('Started on port ' + app.server.address().port);
    });
});

Above situation, the db seems pop out of nowhere

It's the parameter of the function you pass to initializeDb . initializeDb presumable creates a new database instance and passes that instance to the the function you pass to it.

That's just how functions work, they accept parameters that are provided at call time. Only in your example it is not you who calls the function, but another function ( initializeDb ).

Simplified example of a function that takes a callback:

 function answerToEverything(callback) { callback(42); } answerToEverything(answer => console.log(answer)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM