问题
I have a simple timeout
function which wraps an async function with a timeout to ensure that it fails after a preset amount of time. The timeout function is as follows:
export default async function<T = any>(
fn: Promise<T>,
ms: number,
identifier: string = ""
): Promise<T> {
let completed = false;
const timer = setTimeout(() => {
if (completed === false) {
const e = new Error(`Timed out after ${ms}ms [ ${identifier} ]`);
e.name = "TimeoutError";
throw e;
}
}, ms);
const results = await fn;
completed = true;
timer.unref();
return results;
}
I then use this function in this simple code snippet to ensure that the fetch request (using node-fetch
implementation) is converted into a text output:
let htmlContent: string;
try {
htmlContent = await timeout<string>(
response.text(),
3000,
`waiting for text conversion of network payload`
);
} catch (e) {
console.log(
chalk.grey(`- Network response couldn\'t be converted to text: ${e.message}`)
);
problemsCaching.push(business);
return business;
}
When running this code over many iterations, most URL endpoints provide a payload that can be easily converted to text but occasionally one crops up which seems to just hang the fetch call. In these case the timeout does in fact trigger but the TimeoutError
that is thrown is NOT caught by the catch block but instead terminates the running program.
I'm a bit baffled. I do use async/await a lot now but I may still have a few rough edges in my understanding. Can anyone explain how I can effectively capture this error and handle it?
回答1:
A thrown error will only be caught if its directly enclosing function has some sort of error handling. Your anonymous function passed to setTimeout
is not the async
function itself, so the async
function won't stop executing if the separate timeout
throws after some time:
const makeProm = () => new Promise(res => setTimeout(res, 200));
(async () => {
setTimeout(() => {
throw new Error();
}, 200);
await makeProm();
console.log('done');
})()
.catch((e) => {
console.log('caught');
});
This looks like a good time to use Promise.race
: pass it the fetch
Promise
, and also pass it a Promise
that rejects after the passed ms
parameter:
async function timeout(prom, ms) {
return Promise.race([
prom,
new Promise((res, rej) => setTimeout(() => rej('timeout!'), ms))
])
}
(async () => {
try {
await timeout(
new Promise(res => setTimeout(res, 2000)),
500
)
} catch(e) {
console.log('err ' + e);
}
})();
回答2:
This error is happening in a separate call stack, because it's thrown from within a callback. It's totally separate from the synchronous execution flow inside the try
/ catch
block.
You want to manipulate the same promise object from within the timeout or the success callback. Something like this should work better:
return new Promise( ( resolve, reject ) => {
let rejected = false;
const timer = setTimeout( () => {
rejected = true;
reject( new Error( 'Timed out' ) );
}, ms ).unref();
fn.then( result => {
clearTimeout( timer );
if ( ! rejected ) {
resolve( result ) );
}
} );
} );
It would probably work just fine without the rejected
and clearTimeout
too, but this way you ensure that either resolve
or reject
is called, not both.
You'll notice that I didn't use await
or throw
anywhere here! If you are having trouble with asynchronous code, it is better to write it using a single style first (all callbacks, or all promises, or all "synchronous" style using await
).
This example in particular cannot be written using only await
, because you need to have two tasks running at the same time (the timeout and the request). You could probably use Promise.race(), but you still need a Promise
to work with.
来源:https://stackoverflow.com/questions/52197194/try-catch-block-not-catching-async-await-error