简体   繁体   中英

How to retrieve value from process.on in nodejs?

The current code that I am using:

   async function MainFunction(){
        let arrOO;
        process.on('message', (jData) => {
            let sName;
            if(jData.koota){
                sName = jData.koota[0]
            }

            console.log(sName + ' hello!')
            arrOO = sName
        })
        
        console.log(arrOO + ' calling outside of .on')
   }

I am attempting to print jData.koota[0] which is assigned to sName so that it can used in the whole function. In this case, outside of the process.on, I want to print it. When this code is run, 'undefined' is returned at console.log(arrOO + ' calling outside of.on') . How would I call sName outside of process.on?

I will elaborate a little: The sName is not a primitive value thus when u assign sName to ur arr00 you assign the reference to the storage of sName. But since sName is deleted after the function, the arr00 references to an undefined Storage => undefined

async function MainFunction() {
    let arrOO;
    process.on('message', (jData) => {
        let sName
        if (jData.koota) {
            sName = jData.koota[0]
        }

        console.log(sName + ' hello!')
        arrOO = copy(sName)
    })

    console.log(arrOO + ' calling outside of .on')
}

function copy(aObject) { // Deep Clone Object from https://stackoverflow.com/a/34624648/16642626
    if (!aObject) {
        return aObject;
    }

    let v;
    let bObject = Array.isArray(aObject) ? [] : {};
    for (const k in aObject) {
        v = aObject[k];
        bObject[k] = (typeof v === "object") ? copy(v) : v;
    }

    return bObject;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM