I'm confused by this kind of strange behavior from loopback
. I created a very simple remote method as an example below.
Device.getTypes = function(next) {
let result = {0: {val: 10}};
setTimeout(function() {
result[0].wait = true;
}, 10);
console.log(result); // {'0': {val: 10}}
return next(null, result);
};
The console prints out exactly what I expected. result[0].wait
is not defined in this context. But responded JSON data really got me confused.
{
"data":{
"0":{
"val": 10,
"wait": true
}
}
}
I don't understand why "wait": true
was there. I then increased delay time to 100. data[0].wait
was gone. Does loopback
perform a delay in the back?
This behaviour is nothing to do with loopback, it is a node.js feature. node.js in asynchronous in nature(and if you want a synchronous code, you need to use some tricks such as Promise, async libraries, ...). but, that's not just it. console.log is an exception and it is a blocking i/o call, and in your case when your setTimeout is called with a value less than the blocking time, you get "wait": true
in your result, otherwise it returns the result before making that change.