0

HI I have some code to get a json value from my db and then add it to an object but in my if cycle it has the value {"isRoot": "true", "visible": "true"} but after the cycle i do a console.log to this and get undefined...

Database.Services.getServicesMapInfoById(device.id).then(function(mapData){
        if(mapData!=undefined){
            var map = mapData.map;
            console.log("sendDeviceInfo map  >>>>>>>>>>>>>>>>>>>>> ", map);
            sendData.map=map;
            resolve(sendData);
        } else {
            resolve(null);
        }
    }).catch(function (e) {
        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'sendDeviceInfo','FATAL',e);
        return reject(e);
    });

console.log("sendDeviceInfo map --------------------------------->", sendData.map);

Logs:

sendDeviceInfo getServicesMapInfoById map  >>>>>>>>>>>>>>>>>>>>> {"isRoot": "true", "visible": "true"}

sendDeviceInfo map ---------------------------------> undefined

Can anyone help me? I'm returning the value of map with Promises using resolve but this didn't solve my problem...

  • The function is asynchronous. It might not complete until after you log it. – Andrew Li May 27 '17 at 20:59
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – JJJ May 27 '17 at 21:00
  • How can i make it ? I dont get it.. – Catia Matos May 27 '17 at 21:10
  • promises are asynchronous, ` console.log("sendDeviceInfo map --------------------------------->",map);` will always execute before any async code. – 0.sh May 27 '17 at 21:32
  • Maybe the best is to create a array of promises and then execute all with Promise.all ? Im new at node not very good with promises – Catia Matos May 27 '17 at 21:57
  • I can see the log `sendDeviceInfo getServicesMapInfoById map >>>>>>>>>>>>>>>>>>>>>` ptinted before `sendDeviceInfo map ---` it mean `map` has initialize and `getServicesMapInfoById` is "not async" in this case, but `return resolve(map);` recently `resolve` function is blackbox which mayby unset `map` variable – hoangdv May 29 '17 at 04:05

0 Answers0