Categories
JavaScript Answers

How to pass parameters to a promise function with JavaScript?

Sometimes, we want to pass parameters to a promise function with JavaScript.

In this article, we’ll look at how to pass parameters to a promise function with JavaScript.

How to pass parameters to a promise function with JavaScript?

To pass parameters to a promise function with JavaScript, we can create a function that takes the parameters we want to returns the promise.

For instance, we write

const f = (username, password) => {
  return new Promise((resolve, reject) => {
    //...
    if (success) {
      resolve("Stuff worked!");
    } else {
      reject(Error("It broke"));
    }
  });
}
f('username', 'password')

to create the f function that takes the username and password.

In it, we return a promise created by the Promise constructor.

The callback that we pass into Promise does something with username and password and call resolve if success is true and reject otherwise to reject the promise.

Then we call f with the arguments we want.

Conclusion

To pass parameters to a promise function with JavaScript, we can create a function that takes the parameters we want to returns the promise.

Categories
JavaScript Answers

How to get Express to output nicely formatted HTML?

Sometimes, we want to get Express to output nicely formatted HTML.

In this article, we’ll look at how to get Express to output nicely formatted HTML.

How to get Express to output nicely formatted HTML?

To get Express to output nicely formatted HTML, we set the app.locals.pretty option to true.

For instance, we write

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

to set app.locals.pretty to true when our Express app is run in the dev environment.

Conclusion

To get Express to output nicely formatted HTML, we set the app.locals.pretty option to true.

Categories
JavaScript Answers

How to read value from console interactively with Node.js?

Sometimes, we want to read value from console interactively with Node.js.

In this article, we’ll look at how to read value from console interactively with Node.js.

How to read value from console interactively with Node.js?

To read value from console interactively with Node.js, we can use the process.openStdin method.

For instance, we write

const stdin = process.openStdin();

stdin.addListener("data", (d) => {
  console.log(d.toString().trim())
});

to call process.openStdin to accept interactive input from the console.

Then we call stdin.addListener with 'data and a callback to get the entered data d.

The data event is emitted when input is entered.

In the callback, we convert the input data to a string with toString and trim the starting and ending whitespaces with trim.

Conclusion

To read value from console interactively with Node.js, we can use the process.openStdin method.

Categories
JavaScript Answers

How to generate an ObjectId with Mongoose?

Sometimes, we want to generate an ObjectId with Mongoose.

In this article, we’ll look at how to generate an ObjectId with Mongoose.

How to generate an ObjectId with Mongoose?

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

For instance, we write

const mongoose = require('mongoose');
const id = new mongoose.Types.ObjectId();

to create an ObjectId with mongoose.Types.ObjectId and assign it to id.

We don’t need new before mongoose.Types.ObjectId before Mongoose v6.

Conclusion

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

Categories
JavaScript Answers

How to add REST endpoints with Express.js nested router?

Sometimes, we want to add REST endpoints with Express.js nested router.

In this article, we’ll look at how to add REST endpoints with Express.js nested router.

How to add REST endpoints with Express.js nested router?

To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.

For instance we write

const express = require('express');
const app = express();

const userRouter = express.Router();
const itemRouter = express.Router({
  mergeParams: true
});

userRouter.use('/:userId/items', itemRouter);

userRouter.route('/')
  .get((req, res) => {
    res.status(200)
      .send('hello users');
  });

userRouter.route('/:userId')
  .get((req, res) => {
    res.status(200)
      .send(req.params.userId);
  });

itemRouter.route('/')
  .get((req, res) => {
    res.status(200)
      .send(`items ${req.params.userId}`);
  });

itemRouter.route('/:itemId')
  .get((req, res) => {
    res.status(200)
      .send(`item ${req.params.itemId} user ${req.params.userId}`);
  });

app.use('/user', userRouter);

app.listen(3000);

to nest itemRouter in userRoute.

We have

userRouter.use('/:userId/items', itemRouter);

to nest itemRouter in userRouter.

We set mergeParams to true so that the URL from userRouter is combined with the URLs of the routes with itemRouter.

As a result, we get the following results when the following requests are made:

  • GET /user -> hello user
  • GET /user/5 -> 5
  • GET /user/5/items -> items 5
  • GET /user/5/items/6 -> item 6 user 5

Conclusion

To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.