我和诺德在一起.js和TypeScript,我用的是async/await.

async function doSomethingInSeries() {
    const res1 = await callApi();
    const res2 = await persistInDB(res1);
    const res3 = await doHeavyComputation(res1);
    return 'simle';
}

我想为整个功能设置一个超时.也就是说,如果res1需要2秒,res2需要0.5秒,res3需要5秒,我希望有一个超时,3秒后让我抛出一个错误.

正常的setTimeout次调用是一个问题,因为范围丢失:

async function doSomethingInSeries() {
    const timerId = setTimeout(function() {
        throw new Error('timeout');
    });

    const res1 = await callApi();
    const res2 = await persistInDB(res1);
    const res3 = await doHeavyComputation(res1);

    clearTimeout(timerId);

    return 'simle';
}

而我无法用正常的Promise.catch:

doSomethingInSeries().catch(function(err) {
    // errors in res1, res2, res3 will be catched here
    // but the setTimeout thing is not!!
});

有什么解决办法吗?

推荐答案

您可以使用Promise.race来设置超时:

Promise.race([
    doSomethingInSeries(),
    new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 11.5e3))
]).catch(function(err) {
    // errors in res1, res2, res3 and the timeout will be caught here
})

你不能在没有promise 的情况下使用setTimeout.

Typescript相关问答推荐

类型可分配给类型的约束,但可以用不同的约束子类型实例化

在控制器中使用@ DeliverGuards时实现循环依赖项时未定义的依赖项

类型缩小对(几乎)受歧视的unions 不起作用

有没有可能使用redux工具包的中间件同时监听状态的变化和操作

忽略和K的定义

如何在第一次加载组件时加载ref数组

HttpClient中的文本响应类型选项使用什么编码?''

contextPaneTitleText类型的参数不能分配给remoteconfig类型的关键参数'""'''

rxjs forkJoin在错误后不会停止后续请求

具有动态键的泛型类型

如何提取密钥及其对应的属性类型,以供在新类型中使用?

对数组或REST参数中的多个函数的S参数进行类型判断

Next.js错误:不变:页面未生成

带switch 的函数的返回类型的类型缩小

TypeScrip-将<;A、B、C和>之一转换为联合A|B|C

将带点的对象键重新映射为具有保留值类型的嵌套对象

为什么Typescript只在调用方提供显式泛型类型参数时推断此函数的返回类型?

Typescript不允许在数组中使用联合类型

在对象数组中设置值

必须从注入上下文调用Angular ResolveFn-inject()