js如何停止没有resolve或reject的Promise

1,004 阅读1分钟

需求:手动停止没有resolve或reject的Promise

解决方法:trycatch 中如果try中有throw被调用会立即停止 try中 没有 resolve或者 reject 的promise 直接调用catch

代码如下:


function interval() {
    let count = 0;
    setInterval(() => {
        count += 1;
        console.log('count', count);
        if (count > 3) {
            throw count;
        }
    }, 1000);
}

async function main() {
    try {
        console.log('test start');
        interval();
        await new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('222', 222);
                resolve();
            }, 1000 * 10);
        });
        console.log('test ok!');
    } catch (error) {
        console.log('error', error);
    }
}

main();