我知道这不是最漂亮的代码,但由于遗留问题,我需要坚持这个工作流程。
问题是我无法冒泡返回的 promise 核心中可能发生的任何异常。
该代码设计为reject
和resolve
均返回有效数据。因此,如果您将 const CONDITION
更改为 0.4
,我们将收到拒绝。如果 const CONDITION
的值保持在 0.6
,我们将得到一个解决方案。到目前为止,这有效。
但是,如果我们遇到结构性故障,例如在下面的示例中,我们尝试将错误的变量名称传递到拒绝中:
let reasoxxxx = '__FAILED__';
reject({error: reason, data: output});
我无法调用抛出
来引发错误。因此,我收到了通常的丑陋消息,并且无法冒出适当的异常:
Exchange request was rejected due to error(s).
(node:224) UnhandledPromiseRejectionWarning: ReferenceError: reason is not defined
(node:224) 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: 1)
(node:224) [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.
有什么想法吗?截取的代码应该可以工作。
function fakeFetch() {
// Promisify the request.
return new Promise((resolve, reject) => {
// Emulate an asynchroneous fetch.
setTimeout(() => {
let result = 0.4; // Change to 0.4 to trigger a failed fetch.
if (result < 0.5) {;
reject('__FAIL__');
} else {
resolve({name: 'apple', price: '1234.12', time: 1549926859970});
}
}, 2000);
});
}
async function sendExchangeRequest(id, pair, symbols, callback)
{
let err, result
await fakeFetch().then((output) => { result = output }).catch((error) => {err = error})
if(err){
result = 'None'
}else{
err = 'None'
}
callback(err, result)
}
async function fetchExchangeData(id, pair, symbols) {
// Promisify the request.
try {
return new Promise((resolve, reject) => {
try {
// Send the request.
sendExchangeRequest(id, pair, symbols, ((err, output) => {
try{
if(err){
// Soft Failure
console.log('Exchange request was rejected due to error(s).');
reject({error: err, data: output});
}else{
// Success
console.log('Exchange request was successful.');
resolve({error: err, data: output});
}
} catch(error) {
throw error;
}
}));
} catch(error) {
console.log('---\n', error, '\n---');
throw error;
}
});
} catch(error) {
// Bubble up the error?
console.log('+++\n', error, '\n+++');
throw error;
}
}
(async () => {
await fetchExchangeData('myid', 'MYPAIR', 'mySymbol')
.then((result) => console.log(result))
.catch((failure) => console.log(failure))
})();
--- 编辑 (01) ---
我已经更新了我的示例片段,以包含虚假的 API 调用。我希望这能让我的问题更清楚一些。
最佳答案
我认为您不理解异步函数的概念。 fetchExchangeData
中的第一个 try/catch
基本上什么也不做,并且其中没有任何异步内容。初始 promise 中的 try/catch 也几乎没有用,因为我确信 sendExchangeRequest
的大多数/所有问题都可能由错误处理函数 (err)
处理>。至于 try/catch block ,您不应该在 Promise 中抛出错误,而应该拒绝错误(这会使错误冒泡)。仅当您处于异步函数中且不使用回调时才尝试/捕获。
function fetchExchangeData(id, pair, symbols) {
// Promisify the request.
return new Promise((resolve, reject) => {
try {
// Send the request.
sendExchangeRequest(id, pair, symbols, ((err, output) => {
try{
if(err){
// Soft Failure
console.log('Exchange request was rejected due to error(s).');
let reason = '__FAILED__';
reject({error: reason, data: output});
}else{
// Success
console.log('Exchange request was successful.');
resolve({error: '__NONE__', data: output});
}
} catch(error) {
reject(error);
}
}));
} catch(error) {
console.log('---\n', error, '\n---');
reject(error);
}
});
}
关于javascript - 处理返回的 Promise 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54640948/