我无法处理承诺拒绝

问题描述 投票:0回答:1

我有一个分析网站的服务,压缩他们的来源,如CSS文档,图像等。我有2个函数,一个是具有异步回调函数的Socket.IO socket.on()方法。另一个是服务的主要功能。

socket.on('run', async options => {
    debug(`${options.target} Adresine Bir Kullanıcı İstek Yaptı!`);
    let user = null;
    console.log(options);
    if(options.token) {
        user = await User.findById(jwt.verify(options.token, config.get('jwtPrivateKey'))._id);
        options.userId = user._id.toString();
    } else if(options.visitor) {
        user = await Visitor.findById(options.visitor._id);
        if(user.report) {
            return socket.emit('error', new Error('You have exceeded your report limit'));
        } else {
            options.userId = user._id.toString();
        }
    }
    if(options.userId) {
        let userType = await UserType.find({ name: user.type });
        if(userType.length > 0 && ((user.type == 'Visitor' && user.report == undefined) || (user.reports.length < userType[0].rights.reportsLimit.limit || userType[0].rights.reportsLimit.unlimited))) {
            options.rights = userType[0].rights;
            let { error, data } = await wrapper(runService(options.target, options, socket));
            if(error) {
                console.log('Here', error);
                return socket.emit('error', error);
            }
        .
        .
        .
        }
    .
    .
    .
    }
});

在上面的功能中,

let { error, data } = await wrapper(runService(options.target, options, socket));
if(error) {
    console.log('Here', error);
    return socket.emit('error', error);
}

这部分很重要,因为我用我的async函数包装函数调用我的主要异步服务函数runService,该函数名为wrapper。包装函数就是这个;

const wrapper = promise => (
    promise
        .then(data => ({ data, error: null }))
        .catch(error => ({ error, data: null }))
);

在我的主要异步服务函数中,我只抛出一个错误;

async function runService(target, options, socket) {
     throw new Error('any error');
}

但预期产量与实际产量大不相同。这是此代码的输出;

Here Error: any error
    at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
    at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16600) UnhandledPromiseRejectionWarning: Error: any error
    at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
    at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16600) 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: 2)
(node:16600) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate

Node.js进程使用非零退出代码。

我对输出的期望是这样的;

Here Error: any error
    at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
    at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
    at process._tickCallback (internal/process/next_tick.js:68:7)

因为我已经使用我的包装函数处理了承诺拒绝并获得了拒绝,为什么在拒绝时还有2个UnhandledPromiseRejectionWarning错误?

这条线,

return socket.emit('error', error);

不是没有理由的。它应该在if陈述时被称为truthy。为什么不调用这个socket.emit函数?

javascript asynchronous socket.io promise unhandled-exception
1个回答
1
投票

最佳做法是使用try {} catch(){}和async / await。

对于前者

userUtils.signUp = async (userName) => {
try {
    const callFunction = await userUtils.checkExistancy(userName);

    if (!callFunction.isExist) {
        ...
    } else {
        ...
    }
} catch (err) {
    console.log(err);
    throw err;
 }

};

在你的情况下,它会像

socket.on('run', async options => {
try {
    user = await User.findById(jwt.verify(options.token, config.get('jwtPrivateKey'))._id);
    options.userId = user._id.toString();
    return true;
} catch (err) {
    throw err;
}});
© www.soinside.com 2019 - 2024. All rights reserved.