在node.js中处理PromiseRejection

我刚开始第一次使用JavaScript。 从谷歌search,我只能find通过你写的函数处理承诺拒绝的例子。 我的问题是

app.getInput("key"); 

不是由我写的。 我希望能够处理我的代码中被拒绝的承诺。 我的大脑目前在“获取JavaScript”方面遇到了麻烦。

我有这个function(在jovo框架中)

 var content = app.getInput('content'); 

我得到错误“TypeError:无法读取未定义的属性'内容”。 我知道为什么我得到这个错误,我只是想能够处理没有内容的情况。

它也说“未处理的推翻拒绝警告:未处理的承诺拒绝”

我只是想写一些类似的东西

 var content = "null"; content = testFunc().then(() => { console.log('resolved content!'); }).catch((err) => { console.log('error content'); content = "null"; }); function testFunc(){ return app.getInput('content'); } 

奇怪的是,非asynchronous方法返回错误的方式。 无论如何,现在如何处理它


用try / catch包装它

 let content; try { content = app.getInput('content'); // All is ok there ... } catch (err) { ... } 


@ Gabriel Bleu

 function a() { throw new Error('Error'); } async function testFunc() { try { const content = a(); console.log('No error'); return content; } catch(err) { console.log('Error'); return null; } } testFunc(); 

从您的描述和jovo文档 ,我明白, getInput()是一种同步方法。 错误TypeError: Cannot read property 'content' of undefined被引发到调用者(您的代码)。 看起来框架没有正确初始化, undefined东西让我相信。

正如Grégory NEUT先前回答的那样,您可以使用try/catch块来处理它。

 try { content = app.getInput('content'); // All is ok there } catch (err) { // content is unavailable, inspect the error } 

处理诺言最简单的方法是使用asynchronous/等待

 async function testFunc() { try { const content = await app.getInput('content'); return content; } catch(err) { return null; } }