I am a beginner in Angular2 programming. I am trying to write a function that returns a custom promise. It looks like this:
removeItem(item, removeFile: boolean = true): Promise <any> {
// remove the item from the list
let index = this.items.indexOf(item);
if (index > -1) { this.items.splice(index, 1); }
// now if removeFile is true, also physical remove the image
if (removeFile) {
// file.removeFile is basically cordova's file removeFile that returns a promise
return file.removeFile(file.dataDirectory, item.photo[i]);
}
else { // return my own promise so its consistent
return Promise.resolve(); //<---- *THIS*
}
}
The question I have is the line commented as *THIS*
at the bottom. Every example I have seen does a var p = new Promise(resolve, reject)
(one example of many).
Questions:
1) Why do I need to do that? The method above seems to work. I read this SO thread that answers it for another promise framework, but I can't wrap my head around it. Can anyone parse it for me?
2) If I must do a p = new Promise
, I don't want to wrap my entire functionality inside its function like the examples show. Can I just do a return p.resolve() and p.reject() where I need to so I don't add to nesting?
3) To dive a bit more into what @Maximus said:
You need a new Promise whenever there's some async work you wish to perform and then either resolve or reject the promise
Why can't I use the same approach as above (that is, use Promise.resolve/reject)
? For example, lets say I force a custom promise on file.removeFile
(I know this is bad, but I'm just trying to understand why I need a new promise for async work)
if (removeFile) {
file.removeFile(file.dataDirectory, item.photo[i])
.then ({success=>return (Promise.resolve(success);},
{error=>return (Promise.reject(error);});
}
Edit: To clarify, I know perfectly well I don't need to wrap removeFile with my own promise. This was just to give an example of wrapping an async job with my own promise and yet not using new Promise
. In other words, can I learn from an example of an async job that would require me to do a new Promise
and where Promise.resolve
would cause issues?
thanks.