i am trying to insert data from js object in a database using request-promise and update the object with the response of the POST but i don't know how to get my updated object in the last .then()
I don't understand very good promises and have no idea how to manage the if ... else
var rp = require('request-promise')
var test_films = require("./films.json")
function searchPerson(persons, firstname, lastname) {
return persons.filter(function (p) {
return p.firstname == firstname && p.lastname == lastname
})
}
var options = {
uri: 'http://my-api',
json: true
}
rp(options)
.then(function (persons) {
test_films.forEach(function(comedien) {
var found = searchPerson(persons, comedien.firstname, comedien.lastname)
if (found.length === 0) {
console.log('user: ' + comedien.firstname + ' ' + comedien.lastname + ' not found, insert it!')
options = {
method: 'POST',
uri: 'http://my-api',
formData: {
firstname: comedien.firstname,
lastname: comedien.lastname
},
json: true
}
// POST actor and insert id created in array
rp(options)
.then(function (body) {
comedien.person_id = body.id
})
.catch(function (err) {
console.log(err)
})
}
else {
console.log('User: ' + comedien.firstname + ' ' + comedien.lastname + ' already exists!')
comedien.person_id = found[0].id
}
})
return test_films
})
.then(function (result) {
// The object is not updated after i insert it in database
console.log(result)
})
.catch(function (err) {
console.log(err)
})
Thanks for your help !
PS: Tell me why you downvote i an try to improve my question !