Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use async/await in native sql #4227

Closed
pookdeveloper opened this issue Jul 7, 2019 · 4 comments
Closed

Use async/await in native sql #4227

pookdeveloper opened this issue Jul 7, 2019 · 4 comments

Comments

@pookdeveloper
Copy link

How can i use native sql with async/await:
https://loopback.io/doc/en/lb3/Executing-native-SQL.html

Thanks

@sujeshthekkepatt
Copy link
Contributor

sujeshthekkepatt commented Jul 7, 2019

You may wrap it in your own promise function if you don't find corresponding doc for your datasource

@pookdeveloper
Copy link
Author

pookdeveloper commented Jul 7, 2019

Can you set an example?

@sujeshthekkepatt
Copy link
Contributor

const fetchData = ()=> {
return new Promise ((resolve, reject)=>{
YourDatasource.query('query',(err,data)=>{
If(err) return reject (err);
else return resolve(data);
})});

You may try this. Don't forget to replace the query function with your database

@bajtos
Copy link
Member

bajtos commented Jul 9, 2019

As @sujeshthekkepatt wrote:

const result = await new Promise((resolve, reject) => {
  dataSource.connector.execute(sqlStatement, params, options, (err, result) => {
    if (err) reject(err);
    else resolve(result);
  });
});

You may want to write a small helper function:

// usage
const result = await executeAsync(dataSource, sqlStatement, params, options);

// implementation
function executeAsync(dataSource, sqlStatement, params, options) {
  return new Promise((resolve, reject) => {
    dataSource.connector.execute(sqlStatement, params, options, (err, result) => {
      if (err) reject(err);
      else resolve(result);
    });
  });
}

FWIW: For LoopBack 4, we added dataSource.execute API that wraps connector's execute method and adds promise support, unfortunately this is not available in LB3, since this version is in LTS mode.

const result = await dataSource.execute(sqlStatement, params, options);

See loopbackio/loopback-datasource-juggler#1671

@bajtos bajtos closed this as completed Jul 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants