我无法应付诺言

时间:2019-02-15 09:12:37

标签: javascript asynchronous socket.io promise unhandled-exception

我有一项服务,可以分析网站,压缩网站资源(如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);
}

这部分很重要,因为我使用名为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)

因为我已经使用包装函数处理了promise拒绝并捕获了拒绝,为什么拒绝时还有两个UnhandledPromiseRejectionWarning错误?

还行,

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

没有无缘无故打电话。 if陈述为真时应调用该函数。为什么不调用此socket.emit函数?

1 个答案:

答案 0 :(得分:1)

最佳做法是将xargs与async / await一起使用。

例如

try {} catch(){}

就您而言,就像

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

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

};