Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(){})'
like image 615
Joe Avatar asked Aug 03 '16 15:08

Joe


2 Answers

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.

like image 68
kaiser Avatar answered Sep 19 '22 13:09

kaiser


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.
like image 45
Jake Holzinger Avatar answered Sep 17 '22 13:09

Jake Holzinger