Starting to use Promises

The name of the picture


Starting to use Promises



I'm starting to use promises but, I don't really understand this perfectly, can you help me with this. I'm verifying all the data that is sent through the app but just still loading in a buckle and I don't understand why.



This is my code (now I'm just validating the POST method, but I'm just testing with it).


POST




var parse = require('querystring')

/*
check the regular expression of the final value
(not special characters accepted)
*/
var dev = function (data) {
var err = '';
if (data === undefined || data == null || data.length <= 0) {

err += 1;
} else {
if (/[=;(){}/[>'"<]/.test(data)) {
console.log("special char or invalid data ")
console.log(data)
err += 1;

} else {



}
}
return err < 1 ? data : err
}

/*
Verify the type of the value or variable
(recursive functionality)
*/
var verify = function (data) {
if (Array.isArray(data)) {
console.log('array ')
data.forEach(element => {
// console.log(element)
verify(element)
new Promise(function (resolve, reject) {
verify(element, function (err, element) {
if (err) {
reject(err);
} else {
resolve(element);
}
});
})
});
} else if (typeof (data) == 'object') {
//Convert the object on Array to pass this itself to check (recursively)
console.log('is an object')
// console.log(data)
newdata = Object.values(data)
new Promise(function (resolve, reject) {
verify(newdata, function (err, newdata) {
if (err) {
reject(err);
} else {
resolve(newdata);
}
});
})
} else if (typeof (data) == 'function') {
console.log('is a function')
// verify(data())
new Promise(function (resolve, reject) {
verify(data(), function (err, pipe) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
})
} else {
// console.log('last level of data')
return new Promise(function(resolve, reject){
dev(data, function(err, data){
if(err){
reject(err);
} else {
resolve(data)
}
})
})
// dev(data)
}
// return err < 1 ? data : err;
}




/*
Check the method of the request and based on this pass the path on req to verify
(req.body or req.params-req.query)
*/
var controlencoder = function (req, res, next) {

//Print method on console
console.log(req.method)

//check the method
if (req.method == 'PUT' || req.method == 'POST') {
let body = '';
let pipe = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
pipe = parse.parse(body)
console.log(pipe)
return new Promise(function (resolve, reject) {
verify(pipe, function (err) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
}).then(next())

});
} else {
var pipe = req.params
return new Promise(function (resolve, reject) {
verify(pipe, function (err) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
}).then(next())
// console.log(pipe)
}
// var pipe = [req.body, req.params]

}

module.exports = controlencoder;





You have a completely wrong idea about what promises are. This link will teach you a lot.
– Tvde1
5 hours ago




2 Answers
2



In all places where you call verify() and dev() you call it with two arguments, but both functions accept only a single argument. So they will just ignore the functions you pass in.


verify()


dev()



Now the point of the promises is to get rid of these callbacks so I guess you are halfway through in that process. So let's make all of them return Promises, and only accept a single argument.



Let's review the code:



dev(data)


var dev = function (data) {
var err = '';
if (data === undefined || data == null || data.length <= 0) {

err += 1;
} else {
if (/[=;(){}/[>'"<]/.test(data)) {
console.log("special char or invalid data ")
console.log(data)
err += 1;

} else {

}
}
return err < 1 ? data : err
}


err


var err = 0;


/[=;(){}/[>'"<]/



/


/[=;(){}/[>'"<]/


return err < 1 ? Promise.resolve(data) : Promise.reject(err);



verify(data)


var verify = function (data) {
if (Array.isArray(data)) {
console.log('array ')
data.forEach(element => {
// console.log(element)
verify(element)
new Promise(function (resolve, reject) {
verify(element, function (err, element) {
if (err) {
reject(err);
} else {
resolve(element);
}
});
})
});


new Promise(..){...}


verify()


.map()


.forEach()


verify()


Promise


Promise



 


var verify = function (data) {
if (Array.isArray(data)) {
console.log('array ');
return Promise.all(
data.map(element => {
// console.log(element)
return verify(element);
}));
});



Now all items in the array are mapped to an array of the Promise results of all verify() calls, and Promise.all() merges them together so that if even one verify fails, the returned promise fails.


verify()


Promise.all()


} else if (typeof (data) == 'object') {
//Convert the object on Array to pass this itself to check (recursively)
console.log('is an object')
// console.log(data)
newdata = Object.values(data)
new Promise(function (resolve, reject) {
verify(newdata, function (err, newdata) {
if (err) {
reject(err);
} else {
resolve(newdata);
}
});
})



Similar changes here. No need to create new Promise objects when verify already returns a Promise. Let's update to:


Promise


} else if (typeof (data) == 'object') {
//Convert the object on Array to pass this itself to check (recursively)
console.log('is an object');
// console.log(data);
newdata = Object.values(data);
return verify(newdata);



Identical changes here:


} else if (typeof (data) == 'function') {
console.log('is a function')
// verify(data())
new Promise(function (resolve, reject) {
verify(data(), function (err, pipe) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
})



is changed to:


} else if (typeof (data) == 'function') {
console.log('is a function');
return verify(data());



And finally:


} else {
// console.log('last level of data')
return new Promise(function(resolve, reject){
dev(data, function(err, data){
if(err){
reject(err);
} else {
resolve(data)
}
})
})
// dev(data)
}
// return err < 1 ? data : err;
}



is changed to (since dev() also returns a Promise):


dev()


Promise


} else {
// console.log('last level of data')
return dev(data);
}
// return err < 1 ? data : err;
}



controlencoder(req, res, next)


var controlencoder = function (req, res, next) {

//Print method on console
console.log(req.method)

//check the method
if (req.method == 'PUT' || req.method == 'POST') {
let body = '';
let pipe = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
pipe = parse.parse(body)
console.log(pipe)
return new Promise(function (resolve, reject) {
verify(pipe, function (err) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
}).then(next())

});



Change this to:


var controlencoder = function (req, res, next) {

//Print method on console
console.log(req.method)

//check the method
if (req.method == 'PUT' || req.method == 'POST') {
let body = '';
let pipe = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
pipe = parse.parse(body)
console.log(pipe)
return verify(pipe).then(next());
});



And this:


} else {
var pipe = req.params
return new Promise(function (resolve, reject) {
verify(pipe, function (err) {
if (err) {
reject(err);
} else {
resolve(pipe);
}
});
}).then(next())
// console.log(pipe)
}
// var pipe = [req.body, req.params]
}



.. to this:


} else {
var pipe = req.params

return verify(pipe).then(next());
// console.log(pipe)
}
// var pipe = [req.body, req.params]
}



Hope it works :)





Guys, thank you! all is clear now! haha and sorry for that.
– Carlos Sánchez Marroquín
4 hours ago



I just want to share with you the general idea about promises... In your example you are mixing callbacks and promises. Therefore you can't see all the beauty of Promises. In the meantime. Have a look at the following example.


function getCustomer() {
return Promise((resolve, reject) => {
// send async request here
// on response execute resolve(res) or catch error with reject(err)
// for example
request
.get('your_address_here')
.on('response', (res) => {
resolve(res)
})
.on('error', (err) => {
reject(err)
});
})
}

function getCustomerOrders(customer) {
return Promise((resolve, reject) => {
// send async request here
// on response execute resolve(res) or catch error with reject(err)
// for example
request
.get('your_address_here')
.on('response', (res) => {
resolve(res)
})
.on('error', (err) => {
reject(err)
});
})
}



// The power of promises comes when you have to execute function consequently or to resolve them all (Promise.all)


getCustomers()
.then(customer => {
return getCustomerOrders(customer)
})
.then(orders => {
//customer orders here
console.log(orders)
})
.catch(err => {
console.log(err)
})



Or resolve them together if the second promise doesn't rely on the result of the first one


Promise.all([getCustomer(), getCustomerOrders()]).then((values) => {
console.log(values[0]); //is the result of getCustomer()
console.log(values[1]); //is the result of getCustomerOrders()
});



Major disadvantage with Promises are



Error handler is only one Somebody might think this is an advantage, but sometimes you need more then one error handler



The lack of conditionality. For example sometimes you need to resolve promises conditionaly. Then the code lost its beauty and readibility






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP