Reputation: 1513
I am trying to implement file-saving with dialog.showSaveDialog
with the following two approaches:
Approach 1:
const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
},
onRejected => {console.log('Promise rejected')}
);
Approach 2:
const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
}
).catch(err => {
console.log('No file saved');
});
When I click Cancel
instead of Save
in the dialog window, Approach 1 throw me an error message, saying that the promise error is uncaught. Approach 2 works fine (i.e., it displays the text No file saved
.
Why doesn't the pObj
in Approach 1 execute the onRejected
handler? Doesn't then()
method accept two handlers, one for resolved state and one for rejected state? Thanks for explaining.
Upvotes: 0
Views: 180
Reputation: 46
The then() method does indeed accept two handlers, one for resolved state and one for rejected state. The reject
handler is only called when something goes wrong; however, clicking Cancel
instead of Save
doesn't trigger an error, it simply returns a different result through the resolve
handler.
This is clearly explained in the documentation about dialog.showSaveDialog():
Returns
Promise<Object>
- Resolve with an object containing the following:•
canceled
Boolean - whether or not the dialog was canceled.•
filePath
String (optional) - If the dialog is canceled, this will beundefined
.
This should work then (untested):
const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
if (!onResolved.canceled) {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
}
},
onRejected => {console.log('Promise rejected')}
);
Upvotes: 3