I'm still new to all this asynchronous stuff in JavaScript, and I ran into a bit of a confusing situation when working with some promises. Here's my current code:
exists(filename, targetDir){
const filepath = path.join(targetDir || this.getTargetDir(), filename);
// plug in any one method from below
}
When I look into other people's code, I see them resolving values like this (plug into the code above):
// method 1
return request(this.getUrl(filepath))
.then(res => {
return Promise.resolve(res.statusCode === 200);
})
.catch(() => {
return Promise.resolve(false);
});
// method 2
return request(this.getUrl(filepath))
.then(res => {
Promise.resolve(res.statusCode === 200);
})
.catch(() => {
Promise.resolve(false);
});
// method 3
return request(this.getUrl(filepath))
.then(res => {
return res.statusCode === 200;
})
.catch(() => {
return false;
});
// method 4
return new Promise((resolve, reject) => {
request(this.getUrl(filepath))
.then(res => {
resolve(res.statusCode === 200);
}
.catch(() => {
resolve(false);
};
});
Which ones are correct in this case? Which ones are incorrect? Does it depend on the scenario? Which one of these are recommended? A good explanation would be appreciated, thanks!
Clarification: exists
is a class method which returns a Promise which resolves to a boolean, where true
means that the URL exists, and false
means that it doesn't exist.
Clarification #2: exists
should resolve to false
if an error occurs.