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.
I think your code should be restructured like that:
Entry.observe('before save', async (ctx, next) =>{
if(ctx.instance.images){
let data = await(Entry.upload(ctx.instance.images[0].src));
ctx.instance.image = data;
}
});
if your code async code throw error it will be passed to next automatically
loopback3 already support async function.
Entry.findFooById = async (id, cb) => {
const result = await Entry.findById(id);
return result;
};
Entry.findFooById = (id, cb) => {
Entry.findById(id)
.then(result => cb(null, result))
.catch(cb);
};
These two functions will accomplish the same functionality.
@yqrashawn
Thanks but am curious how would you return multiple returns using that way?
For instance, if we have this code
module.exports = function(Person){
Person.greet = function(msg, cb) {
cb(null, 'Greetings... ' + msg, 'Greeting2 Message');
}
Person.remoteMethod('greet', {
accepts: {arg: 'msg', type: 'string'},
returns: [
{arg: 'greeting', type: 'string'},
{arg: 'greeting2', type: 'string'}
]
});
};
How can I use async await and return 2 values?
Nevermind, I found out how to do it by trying multiple options
You can replace
cb(null, 'Greetings... ' + msg, 'Greeting2 Message');
into
return ['Greetings... ' + msg, 'Greeting2 Message'];
Most helpful comment
Nevermind, I found out how to do it by trying multiple options
You can replace
into