Timotei Manolache Timotei Manolache - 2 years ago 90
Node.js Question

How do I send the result of a function to a third one without a return?

I'm trying to call a Cloudant map function in a NodeJS service for the purposes of a unit test.

I've created my own emit function but I still can't get the view to return what I need.

const data = {
"_id": "68e3d2807c0faa169d504068db99e03f",
"_rev": "2-c3b3249a2eb090e87dc4c053712691c3",
"type": "user",
"name": "Whatever",
"email": "Whatever@google.com",
"cn": "5517605X",
"phone": null,
"deleted": true
}

const emit = function (arg1, arg2) {
return { key: arg1, value: arg2 };
};

var map = function (doc) {
if (doc.type && doc.type === 'user') {
emit([doc.cn, doc.deleted], doc);
}
};

const result = map(data);
console.log(result);


JSFiddle to what I'm trying to do. I know I can fix it by just adding a return in front of the emit function but I'm not able to edit the map function as I'm getting the view straight from Cloudant.

Is there a way I can still make this work?

Answer Source

but I'm not able to edit the map function

Then you can't change the map function's return. Calling it will always result in undefined. There's no way around that other than changing map (or using something else).


In the specific case you've shown, emit could close over result and set it directly if you moved the result declaration up above emit and made it a let:

let result;
const emit = function (arg1, arg2) {
    result = { key: arg1, value: arg2 };
    return result;
};

var map = function (doc) {
    if (doc.type && doc.type === 'user') {
        emit([doc.cn, doc.deleted], doc);
    }
};

map(data);
console.log(result);

...but that's very specific to that code, and even if you don't go for a full-on functional programming approach, it's not great to have functions with side-effects like that. But sometimes needs must.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download