I am really struggling with integrating Javascript promises into my code and would be grateful for some help on this.
I have this simple function which is part of a program that handles creating, reading, updating and deleting of files, so I decided to change it from using callbacks to using promises.
this is the delete function:
lib.delete = (dir, file, callback) => {
/* unlink the file */
fs.unlink(lib.baseDir + dir + '/' + file + '.json', (err) => {
if (!err) {
callback(false);
} else {
callback(' Error deleting file');
}
});
};
The way I was going to do this, was to enclose the async part in a promise:
lib.delete = (dir, file, callback) => {
/* unlink the file */
return new Promise((resolve, reject) => {
fs.unlink(lib.baseDir + dir + '/' + file + '.json', (err) => {
if (!err) {
resolve(false);
} else {
reject(err);
}
});
});
});
But this all seems wrong because here I'm defining the promise, but here is actually where I actually want to use it, i.e. deal with the result of it with .then
.
I am missing something basic here, I have this feeling that I need to change the way I am thinking about the all delete function... Any help would be appreciated.
If you want to use Promise
you don't have pass a callback
into these arguments, it's the goal of promise : call any function you want after resolve/reject.
For example :
With callback :
lib.delete = (dir, file, callback) => {
/* unlink the file */
fs.unlink(lib.baseDir + dir + '/' + file + '.json', (err) => {
if (!err) {
callback(false);
} else {
callback(' Error deleting file');
}
});
};
lib.delete('./dir', 'filname.txt', function(res){
console.log(res);
})
With promise
lib.delete = (dir, file) => {
return new Promise((resolve, reject) => {
fs.unlink(lib.baseDir + dir + '/' + file + '.json', (err) => {
if (!err) {
resolve(false);
} else {
reject(err);
}
});
});
});
lib.delete('./dir', 'filname.txt')
.then( () => console.log("No error i'm happy")
.catch( (err) => console.log('Error', err)
then
: exec when resolve is trigger
catch
: exec when reject is trigger
I hope it's gonna help you !