khernik
khernik

Reputation: 2091

Loopback support for async/await

I'm using loopback 3 to build a REST service, and I want to use the async/await instead of having to use the callbacks. So instead of doing that:

MyModel.myFunction = (callback) => {
  MyModel.find({where: {id: 2}}, (e, data) => {
    if (e) return callback(e);
    callback(null, data);
  });
};

I would greatly prefer to do:

MyModel.myFunction = async (callback) => {
  try {
    const data = await MyModel.find({where: {id: 2}});
    callback(null, data);
  } catch (e) {
    console.error(e);
    callback(e);
  }
};

The callback approach works perfectly - async/await however gives numerous errors:

What's wrong? I cannot get through this issue.

Upvotes: 7

Views: 7006

Answers (3)

hasnain haider
hasnain haider

Reputation: 1

An easier way would be to just use a function to resolve your promise and just pass the db query to it, like so.

async function ReturnWithResolvedPromise(dbQuery) {
try {
    return Promise.resolve(dbQuery);
} catch (e) {
    return Promise.reject(e);
}}

and then call this like so

let result =    await ReturnWithResolvedPromise(await Users.count({where: {Region: 'UK'}}));

Upvotes: 0

Maxim Sharai
Maxim Sharai

Reputation: 614

Some refactoring:

MyModel.myFunction = async () => {
  try {
    const data = await MyModel.find({where: {id: 2}});
    return data; // it's enough as the async means it returns a promise
  } catch (e) {
    console.error(e);
    throw e;
  }
};

This one in case if you don't need to log an error (loopback error handler logs it instead of you):

MyModel.myFunction = async () => {
  return MyModel.find({where: {id: 2}});
};

Upvotes: 11

khernik
khernik

Reputation: 2091

Looks like I was simply mixing two concepts, this is the solution:

MyModel.myFunction = async (callback) => {
  try {
    const data = await MyModel.find({where: {id: 2}});
    return Promise.resolve(data);
  } catch (e) {
    console.error(e);
    return Promise.reject(e);
  }
};

Upvotes: 1

Related Questions