Joe
Joe

Reputation: 4254

Run async code from command line, node js

I have a function that generates some test data and inserts it to a mongodb:

'use strict';
const CvFaker = require('./cv-faker');
const mongoose = require('mongoose');
require('../models/cv_model.js');

module.exports.init = function(){
  var cvfaker = new CvFaker();
  cvfaker.genCvs(100);

  mongoose.model('cv').create(cvfaker.cvs, (err, createdCvs) => {
    if(err){
      console.log('something went wrong');
    }

  })
};

I want to execute this code from the command line:

node -e 'require("./create-mock-db").init()'

The function executes, but it does not wait for the function to complete since it is async. How do I make it wait for the function to complete?

This is not working either:

module.exports.init = function(cb){ ...
..
cb();

node -e 'require("./create-mock-db").init(function(){})'

Upvotes: 10

Views: 14567

Answers (3)

Raphi OKG
Raphi OKG

Reputation: 93

To add to Kaiser's answer, if you are on Windows using cmd, the single/double quotes are important. Put the double quotes on the outside, i.e.

node -e "require('./test').demo()"

Upvotes: 0

Jake Holzinger
Jake Holzinger

Reputation: 6063

The node process will not exit until the event queue is empty. The event loop uses the event queue to make asynchronous execution possible.

It's pretty simple to verify that this is not an issue with executing asynchronous code.

node -e "setTimeout(() => console.log('done'), 5000)"

This example takes 5 seconds to run, as you would expect.


The problem with your code is the fact that you never establish a connection with the database. The model.create method doesn't do anything until there is a connection, therefor nothing ever gets queued and the process is free to exit.

This means your code needs to change to do two things:

  1. Connect to the database so that the model.create method can execute.
  2. Disconnect from the database when model.create is complete so the process is free to exit.

Upvotes: 3

kaiser
kaiser

Reputation: 22363

As this answer might come up for more people…

// test.js
const request = require('request');
const rp = require('request-promise');

const demo = module.exports.demo = async function() {
  try {
    const res = await rp.post( {
      uri: 'https://httpbin.org/anything',
      body: { hi: 'there', },
    }, function (error, response, body) {
      return error ? error : body;
    } )
    console.log( res )
    return res;
  }
  catch ( e ) {
    console.error( e );
  }
};

Call it like this:

$ node -e 'require("./test").demo()'

Sidenote:

it does not wait for the function to complete since it is async

It's not async. You might call asynchronous functions, but you are not treating them as such and not awaiting any result.

Upvotes: 2

Related Questions