I am learning promises in node js.I have written a piece of code as below.
var request = require("request");
var userDetails;
function getData(url) {
// Setting URL and headers for request
var options = {
url: url,
headers: {
'User-Agent': 'request'
}
};
// Return new promise
return new Promise(function (resolve, reject) {
// Do async job
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
})
})
}
var errHandler = function (err) {
console.log(err);
}
function main() {
var userProfileURL = "https://api.githshub.com/users/narenaryan";
var dataPromise = getData(userProfileURL);
// Get user details after that get followers from URL
var whichPromise = dataPromise.then(JSON.parse)
.then(function (result) {
userDetails = result;
// Do one more async operation here
console.log("then1")
var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
return anotherPromise;
})
.then(function (data) {
return data
});
console.log(whichPromise)
whichPromise.then(function (result) {
console.log("result is" + result)
}).catch(function (error) {
console.log("Catch" + error)
});
}
main();
Now this works just fine. I have queries in this regard.
1.How JSON.Parse able to parse data without getting json string in argument.
var whichPromise = dataPromise.then(JSON.parse)
2.If i put a wrong url in below line
var userProfileURL = "https://api.githshub.com/users/narenaryan";
then it's then block will not work because DNS will not be resolved & should get an error which means
var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
return anotherPromise;
will not return any value and whichPromise
will not have any reference.
but if call below code
whichPromise.then(function (result) {
console.log("result is" + result)
}).catch(function (error) {
console.log("Catch" + error)
});
here whichPromise is able to call the catch block. can someone explain why ?