Categories
JavaScript Answers

How to import a JavaScript package from a CDN or script tag in React?

To import a JavaScript package from a CDN or script tag in React, we get the library from window.

For instance, we write

<script src="https://cdn.dwolla.com/1/dwolla.js"></script>

to add the dwolla library with a script element.

Then we get the dwolla library with

const dwolla = window.dwolla;
Categories
JavaScript Answers

How to replace callbacks with promises in Node.js?

To replace callbacks with promises in Node.js, we use the util.promisify method.

For instance, we write

const util = require("util");

const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);

exports.getUsersAsync = async () => {
  await connectAsync();
  return queryAsync("SELECT * FROM Users");
};

to call util.promisify with the connectAsync and queryAsync methods to convert them to functions that return promises.

And then we call connectAsync to return a promise and use await to run the promise.

Categories
JavaScript Answers

How to install the exact package version specified in package.json with Node.js npm install?

To install the exact package version specified in package.json with Node.js npm install, we use the --save-exact option.

For instance, we run

npm install --save --save-exact react

to install the exact version of the react package listed in package.json with --save-exact.

Categories
JavaScript Answers

How to get the objectID after saving an object in Mongoose and JavaScript?

To get the objectID after saving an object in Mongoose and JavaScript, we get the saved document from the returned promise.

For instance, we write

const gnr = new Band({
  name: "Band",
  members: ["Axl", "Slash"],
});

const doc = await gnr.save();

to create a new Band.

And then we call save to return a promise with the saved document.

We use await to get the document from the promise.

Categories
JavaScript Answers

How to use multiple parameters in URL in Node.js Express?

To use multiple parameters in URL in Node.js Express, we add multiple parameter placeholders.

For instance, we write

app.get("/fruit/:fruitName/:fruitColor", (req, res) => {
  const data = {
    fruit: {
      apple: req.params.fruitName,
      color: req.params.fruitColor,
    },
  };

  send.json(data);
});

to add the fruitName and fruitColor URL placeholders for the get route.

Then we get their values from the req.params object.