Danny Sun Danny Sun - 1 month ago 8
Node.js Question

Appending Key/Value to object inside of Promise

So I am currently attempting to modify a global object within a promise using the code below, however, when i console.log the object at the end, it returns 'undefined' for the key of 'id'. I'm a little confused as to why inside the success block of a promise it isn't setting the new key and value within the patient object. Thanks in advance!

patient = { first_name: first_name, last_name: last_name, gender: gender, dob: dob }

postgres.findPatient(patient)
.then(function(success){

patient.id = success.id

})
.catch(function(err){
if (err.received === 0) {
postgres.createPatient(patient)
.then(function(success){
postgres.findPatient(patient)
.then(function(success){
patient.id = success.id
})
})
.catch(function(err){
if (err) console.log(err);
})
}
})

console.log(patient) // yields

patient = {
first_name: 'billy,
last_name: 'bob',
gender: 'm',
dob: '1970-01-01' }

Answer

Promises are asynchronous. You will only see the id key on the patient after the .then() has finished executing. Top level code is executed synchronously, so you're looking for the id before the promise has finished. You can only access the id inside a chained callback like .then() when the promise has guaranteed to finish.