Promise链式调用失效?为何代码报Cannot read property 'then' of undefined
解决「Cannot read property 'then' of undefined」的问题
嘿,我太懂你这种困惑了——明明哈希值能正常打印,却突然冒出这个报错,简直摸不着头脑!其实核心原因特别简单:你调用bcrypt.hash的那个函数,没有返回这个Promise实例。
我给你举个典型的错误写法,你看看是不是和你的代码情况一致:
function hashMyPassword(password) { // 这里调用了bcrypt.hash,内部的then确实能正常打印哈希值 bcrypt.hash(password, 10).then(hash => { console.log('哈希值:', hash); }); // 注意!这个函数没有return任何内容,默认返回undefined } // 当你这样调用时,就会触发报错 hashMyPassword('my-password').then(result => { console.log('外部拿到的结果:', result); });
为什么哈希值能打印?因为bcrypt.hash本身的Promise是正常执行的,它内部的.then回调会被触发,所以你能看到输出。但外层的hashMyPassword函数没有返回这个Promise,所以当你在外部尝试对它的返回值调用.then时,本质上是在对undefined调用.then,这就会抛出你看到的错误。
正确的写法有两种:
1. 直接返回bcrypt.hash的Promise
function hashMyPassword(password) { // 关键:把bcrypt.hash的Promise返回出去 return bcrypt.hash(password, 10).then(hash => { console.log('哈希值:', hash); return hash; // 可选,如果需要让外部拿到哈希值的话 }); } // 现在调用就正常了 hashMyPassword('my-password').then(result => { console.log('外部拿到的哈希值:', result); });
2. 使用async/await语法(更直观)
async function hashMyPassword(password) { const hash = await bcrypt.hash(password, 10); console.log('哈希值:', hash); return hash; // async函数会自动把返回值包装成Promise } // 调用方式和之前一样 hashMyPassword('my-password').then(result => { console.log('外部拿到的哈希值:', result); });
这样调整后,外部调用的.then就能正确绑定到bcrypt.hash的Promise上,不会再出现那个报错啦!
内容的提问来源于stack exchange,提问作者zzzz
相关产品推荐
相关产品推荐

