I wrote the code below:
function readFile(path) {
return new Promise(function(resolve, reject){
if(!fs.existsSync(path))
return reject(new Error("data.json file does not exist"));
else {
console.log("File is actually found!");
return Promise.resolve("File found");
}
})
}
readFile(path)
.then(value => {
console.log(value);
})
.catch(err => {
console.log(err);
})
What happens:
If the file exists, the console output is just File is actually found!
If the file does not exist, it displays: data.json file does not exist
along with the error stack.
What I want:
When the file does exist, I want File found
to be displayed in addition to File is actually found!
. I found that this happens when I replace return Promise.resolve("File found");
with just resolve("File found");
or even return resolve("File found");
.
Question:
What really is the difference between resolve()
and Promise.resolve()
? Why does returning or not returning not make a difference (I guess it is because it is the last statement in the function).
Note: I use existsSync()
because I want the process to be blocking until the file is actually read, because if the file is not read, then there is nothing to be done! I understand promise might not be needed here, but I still use it because that is what I am trying to learn.
Thanks!
Edit: One more question - what actually should be rejected and resolved? I mean, in the code above, I pass new Error(...)
to reject()
and a string to resolve()
- is that alright?