在Node.js的派生子流程中使用全局流程对象

时间:2019-05-25 17:06:11

标签: node.js mongodb mongoose

我正在尝试使用fork()运行子进程。目的是在该子进程中执行一些与数据库相关的工作。我无法访问process内部的全局mongoose then call对象。我也尝试过使用async-await,但是await调用之后的任何内容都永远不会执行,并且以某种方式在不同models上尝试过的所有猫鼬查询都不会返回任何内容

下面是该代码的最新版本

父文件中的功能

async doSomething(user) {
        const forked = fork(path.resolve(__dirname, 'child.js'), [`--userId=${user._id}`]);


        forked.on('message', (msg) => {
            console.log(msg);
        });

        forked.on("error", (err) => {
            console.log(err);
        });

        forked.on("exit",(code,signal)=>{
           console.log("Code",code);
           console.log("Signal",signal);
        });
        forked.send("Hello")
    }

child.js文件源代码

const argv = require('yargs').argv;

import {ObjectId} from 'mongodb'

import User from '../../db/user/user';

process.send(`USER ID: ${argv.userId}`); //works

setInterval(() => {
    execute(process); //has to pass to process object to function to
                      //be available, i.e. can't get process.send to
                      //work inside then calls and normal function 
                      //calls
}, 2000);

async function execute(process) {

    process.send("Hello"); //works

    let users = await User.find({}).exec(); //returns empty object to parent process

    process.send(users); //logs {} in console

    if (users && users.length > 0) {
        users.forEach((user) => {
            process.send(user) //doesnt work because perhaps users is {}
        })
    } else {
        process.exit(404); //works
    }

}

    //created a separate function 
   //because **process** was not available inside then call's
   //resolve callback or catch call
   //tried to call it for fetching users but still failed
  //returns empty object

    async function getUsers() {
        return User.find({creatorID: {$eq: ObjectId(argv.userId)}}).then((users) => {
            return users;
        }).catch(err => {
            return err;
        })
    }

这些数据库查询出了什么问题?为什么在thennables中甚至在一个简单函数中都无法调用全局过程对象的方法

0 个答案:

没有答案