Intellij Idea warning - “Promise returned is ignored” with aysnc/await

后端 未结 6 1439
抹茶落季
抹茶落季 2020-12-29 19:02

I\'m using Express.js in my code with Node.js v7.3. In this I\'ve created a User Router which forwards the requests to my User Controlle

相关标签:
6条回答
  • 2020-12-29 19:46

    another way to get rid of the warning is defining an empty then():

    userController.login(req, res); // <- Get the warning here

    userController.login(req, res).then(); // <- No warning

    0 讨论(0)
  • 2020-12-29 19:47

    router.post('/login', function (req, res, next) {
        void userController.login(req, res); // I get the warning here
    });

    You should use "void" operator.

    0 讨论(0)
  • 2020-12-29 19:48

    The userController.login() function returns a promise, but you're not doing anything with the result from the promise by utilizing its then() function.

    For example:

    userController.login(req, res).then(() => {
        // Do something after login is successful.
    });
    

    or in the ES2017 syntax:

    await userController.login(req, res);
    

    If you don't actually want to do anything there, I guess you can just ignore the warning. The warning is mostly there because not using the then() function on a promise is usually a code smell.

    0 讨论(0)
  • 2020-12-29 19:50

    if you are really manic as me and the then() is not required but you need the warning to go away, a possible solution is:

    functionWithAsync.error(console.error);
    
    0 讨论(0)
  • 2020-12-29 20:05

    The thing is I'm not even returning anything from the login() method.

    A function declared "async" returns a Promise by definition. See for example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    However the IDEA warning is only an inspection. You can press "alt-enter, right" on the warning and change the inspection level to make the warning go away. The inspection is in the "JavaScript -> Probable bugs" category and is named "Result of method call returning a promise is ignored".

    0 讨论(0)
  • 2020-12-29 20:07

    I'm using try{} catch(e){} in NodeJs and found that simply adding Error() to the end of the function fixed the warning.

    Full code:-

    someArray.forEach(async (arrayValue) => {
        try {
            const prodData = await myAsyncFunc(arrayValue);
        } catch(e) {
            console.error(`Error: ${e}`);
        }
    }, Error());
    
    0 讨论(0)
提交回复
热议问题