I have this bit of code:
var w = flow.get("who_1") || {};
var p = msg.payload;
if (w.length > 0)
{
// do stuff here.
The idea is that at/on first invocation the flow.get("who_1")
will not be set.
I was under the impression that the || {}
implies that if there isn't a value, set it to null.
(Don't know if there should be a space between the {
and }
.
The situation is that if the variable is not assigned, it needs to do the do stuff here part.
It isn't.
variable === null
is the usual way of testing. A switch node is capable of it directly, flow.variable
with rule “is null” or “is not null”
1 Like
Alas because of a multitude of things, I am going with a function
node rather than a lot of switch
nodes one after the other.
It has been suggested I use the FSM
node. But there are two I can see and both are old.
I know nothing about them and reading their descriptions, it is a whole new world to learn if I want to use them.
This is the new code:
var w = flow.get("who_1")|| {};
var p = msg.payload;
if (w === null)
{
//
node.warn("1");
return [msg,null];
} else
if (w == p)
{
//
node.warn("1");
return [msg,null];
} else
node.warn("2");
return [null,msg];
with nothing being set in flow.get('who_1)
I would hope that 1
is the output.
Alas it isn't.
I am getting 2
used and I am not seeing why.
1 Like
Not quite - and that is the source of the issue in your Function.
When you have statement like:
var A = B || C;
Then A
is assigned the value of B
if it has a true-like value. But if B
has a 'false-like' value (0
, null
, undefined
, ""
, false
) then A
is given the value of C
.
So where you have var w = flow.get("who_1")|| {};
, if the flow context value who_1
is not defined, then w
is given the value {}
- which is an empty JavaScript object, not null
.
If you have not yet set a value in flow.who_1, then the flow.get()
statement will return undefined
.
So the proper way to do the check you are doing is:
// don't use the ||{} trick as you want to know if it is undefined
var w = flow.get("who_1");
var p = msg.payload;
// Check if it is undefined, not null
if (w === undefined)
{
//
node.warn("1");
return [msg,null];
} else if (w == p) {
//
node.warn("1");
return [msg,null];
} else {
node.warn("2");
}
return [null,msg];
4 Likes
For me this worked as as the debug shows ''null'' and the default variable ''null'' does the job. When trying to match if there is msg.payload.length I got this ""TypeError: Cannot read property 'length' of null"".
if (msg.payload=== null) {
msg.payload = 0;
}
return msg;