dyaa
dyaa

Reputation: 1450

loopback async/await UnhandledPromiseRejectionWarning issue

In loopback 3 When i implement async/await in the before save Operation hook

Entry.observe('before save', async (ctx, next) =>{

    if(ctx.instance.images){
        Entry.upload(ctx.instance.images[0].src).then(data => {
            ctx.instance.image = data;
        });
    }
});

the console print this error

(node:29323) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
(node:29323) 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.

How can i get rid of this issue!?

PS. i cant figure out where's that promise, and this message disappear once i remove the async/await.

Upvotes: 2

Views: 2303

Answers (2)

rigobcastro
rigobcastro

Reputation: 1257

Use try/catch block and always return a Promise resolved or rejected when declare async function (or Promise function)

Entry.observe('before save', async (ctx) =>{
    try {
      ctx.instance.image = await Entry.upload(ctx.instance.images[0].src)
    } catch(error){
      return Promise.reject(error)
    }

    return Promise.resolve()
});

Upvotes: 1

xerq
xerq

Reputation: 2792

You need to specify .catch for the Entry.upload promise.

Entry.upload(ctx.instance.images[0].src).then(data => {
        ctx.instance.image = data;
    }).catch(console.error);

Some older versions of NodeJS probably won't have that error. You need to always use catch for promises, otherwise the app will crash.

Upvotes: 2

Related Questions