gpt4 book ai didi

javascript - 用dialog.showSaveDialog实现 promise 拒绝

转载 作者:行者123 更新时间:2023-12-03 12:30:03 25 4
gpt4 key购买 nike

我正在尝试通过以下两种方法来实现dialog.showSaveDialog的文件保存:
方法1:

const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
},
onRejected => {console.log('Promise rejected')}
);
方法2:
const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
}
).catch(err => {
console.log('No file saved');
});
当我在对话框窗口中单击 Cancel而不是 Save时,方法1向我抛出一条错误消息,提示未捕获到Promise错误。方法2运作良好(即显示文字 No file saved
为什么方法1中的 pObj不执行 onRejected处理程序? then()方法不接受两个处理程序,一个用于解决状态,一个用于拒绝状态吗?感谢您的解释。

最佳答案

then()方法确实确实接受两个处理程序,一个用于解决状态,一个用于拒绝状态。仅当出现问题时才调用reject处理程序;但是,单击Cancel而不是Save 不会触发错误,它只是通过resolve处理程序返回了不同的结果。
有关dialog.showSaveDialog()的文档中对此进行了明确说明:

Returns Promise<Object> - Resolve with an object containing thefollowing:

canceled Boolean - whether or not the dialog was canceled.

filePath String (optional) - If the dialog is canceled, this will be undefined.


然后,这应该起作用(未经测试):
const pObj = dialog.showSaveDialog(window, options);
pObj.then(
onResolved => {
if (!onResolved.canceled) {
filename = onResolved.filePath;
fs.writeFileSync(filename, arg);
}
},
onRejected => {console.log('Promise rejected')}
);

关于javascript - 用dialog.showSaveDialog实现 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64503349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com