所以,我一直在尝试复制这段代码: https://github.com/sindresorhus/np/blob/370ef638344ab7115c956b75dc2823850084da39/index.js#L16
它有效。但是,如果承诺失败,我会得到一个“未处理的承诺”警告。如果有的话,catch语句在哪里属于这样的东西?有没有更好的方法来获取这样的信息?
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)
(node:48454) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
答案 0 :(得分:0)
只需在await调用周围放置一个try / catch块。这应该与调用Promise并提供catch函数相同。
因此,如果您有一个函数getPromise()
返回一个承诺,那么您只需执行此操作。
async function asyncFunction() {
try {
const result = await getPromise();
} catch (error) {
// Add your error handling code here
}
}