Electron中keytar模块使用问题:如何获取实际密码值?
Promise { <pending> }的问题 Hey there! I see the issue you're running into—let's break this down and fix it.
The reason you're seeing Promise { <pending> } in your console is because all keytar methods (including getPassword and setPassword) are asynchronous functions that return Promises, not immediate values. When you log the result directly, you're just logging the pending Promise object instead of waiting for it to resolve to the actual password.
Here are two straightforward ways to get the real password value:
1. 使用 async/await(推荐,代码更简洁易读)
Wrap your keytar calls in an async function, then use await to wait for each Promise to resolve. Don't forget error handling with try/catch!
const keytar = require('keytar'); async function handlePasswords() { try { // 先等待密码设置完成 await keytar.setPassword('KeytarTest', 'AccountName', 'secret'); // 等待Promise解析,获取真实的密码值 const secret = await keytar.getPassword('KeytarTest', 'AccountName'); console.log(secret); // 现在会输出'secret'了! } catch (error) { console.error('密码操作出错:', error); } } // 调用这个异步函数执行逻辑 handlePasswords();
2. 使用 Promise 的 .then() 链式调用
如果你不想用async/await,可以通过链式调用.then()来处理解析后的值:
const keytar = require('keytar'); // 先设置密码,再获取密码 keytar.setPassword('KeytarTest', 'AccountName', 'secret') .then(() => { return keytar.getPassword('KeytarTest', 'AccountName'); }) .then(secret => { console.log(secret); // 解析完成后输出'secret' }) .catch(error => { console.error('密码管理出错:', error); });
重要提示
一定要等setPassword执行完成后再调用getPassword——如果跳过这一步,你可能会在密码还没保存成功时就尝试获取,导致意外结果。
内容的提问来源于stack exchange,提问作者ykonda

