I have this snippet of code in node.js, similar to javascript, well what happens is that it uses asynchronous methods to perform a validation of fields that is entered through a csv file, therefore I must analyze value by value of the fix _data
, I also have in object user
where it contains the property of user
as global variable.
The problem is when I want to change the attributes of these properties within methods I get undefined error when I use this
.
How should I use promise?
this.user = {
nombre: "",
descripcion: "",
email: "",
fotografia: "",
},
isEmpty: function (str) {
return (!str || 0 === str.length);
},
getUrlPath: function (fotografia) {
return firebaseApp.database().ref("user").orderByChild("fotografia").equalTo(fotografia).on("child_added", function (snapshot) {
this.user.fotografia = snapshot.fotografia; **//error, undefined**
console.log(" su correo es " + snapshot.val().email);
// salida su correo es '[email protected]'
});
},
//devuelve un correo desde firebase
_getEmail: function (_email) {
// var result = false;
return firebaseApp.database().ref("user").orderByChild("email").equalTo(_email).on("child_added", function (snapshot) {
this.user.email = snapshot.email; **//error, undefined**
console.log(" su correo es " + snapshot.val().email);
// salida su correo es '[email protected]'
});
// return result;
};
validar: function (_data) {
var partialErrors = "";
var that = this;
//fotografia
this.getEmail(_data[3])).then(function (_valid) { **//aca funciona el this**
if (!_valid) {
partialErrors = partialErrors + "'" + _data[3] + "'" + " url no valida | ";
}
// nombre
}).then(function (value) {
if (this._isEmpty(_data[1])) { **//error, undefined**
partialErrors = partialErrors + "'" + _data[2] + "'" + " valor incorrecto | ";
}
})
//descripcion
.then(function (value) {
if (this._isEmpty(_data[2])) { **//error, undefined**
partialErrors = partialErrors + "'" + _data[2] + "'" + " valor incorrecto | ";
}
//email
}).then(function (value) {
//obligue que ingresara aunque sea valida
if (this._getEmail(_data[2])) { **//error, undefined**
console.log("valor : " + this.user.email); **//error, undefined**
partialErrors = partialErrors + "'" + _data[2] + "'" + " es incorrecto, sólo válido <[email protected]> | ";
}
}).catch(function (error) {
console.log(error);
});
if (partialErrors.length > 0) {
//error, undefined** No funciona el this
this.errorFields.push("En " + _data + " se econtro errores en " + partialErrors);
console.log(this.errorFields);
}
}