Loopback: async function - callback called after finished

Created on 14 Mar 2018  ·  2Comments  ·  Source: strongloop/loopback

Description/Steps to reproduce

I'm defining a async remote method and when I call the callback function with no Errors 'Callback was already called'. But if the callback has an Error, it all goes well.

Function with no errors:

Client receives 'ok' but server's console shows 'Error: Callback was already called.'
Test.async_returnCB = async (cb) => { cb(null, "ok") }

Console:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Function with Error:

Client receives Error message, and nothing shows on server's console
Test.async_returnError = async (cb) => {let err = new Error() err.statusCode = 400 cb(err)}

Console:

Unhandled error for request POST /tests/async_returnError ... The usual stuff

Link to reproduction sandbox

https://github.com/israelglar/loopback-async-error

Expected result

No Errors

Additional information

linux x64 8.9.4

[email protected] /home/USER/loopback-sandbox
├── [email protected]
├── [email protected]
├── [email protected]

Most helpful comment

@israelglar async functions are returning a promise which is handled by LoopBack, you must not use the callback. Simply return the value directly.

Test.async_returnCB = async () => "ok";

To report an error, return a rejected promise or throw the error directly.

Test.async_returnError = async () => {let err = new Error() err.statusCode = 400 throw err}

All 2 comments

Is there a solution to this?

@israelglar async functions are returning a promise which is handled by LoopBack, you must not use the callback. Simply return the value directly.

Test.async_returnCB = async () => "ok";

To report an error, return a rejected promise or throw the error directly.

Test.async_returnError = async () => {let err = new Error() err.statusCode = 400 throw err}
Was this page helpful?
0 / 5 - 0 ratings