简体   繁体   中英

how can I await a sparql request and set a variable in a nodejs app?

I'm a newbie to both sparql and nodejs and want to query dbpedia to set a variable and pass it on to the front end. However if I run my code I can console.log the requested data but I don't get it over to the frontend. I m using the sparql-http-client js. I'd appreciate any hint. I do have difficulties in getting my head around async.

const SparqlClient = require('sparql-http-client');

exports.sparql = async (req,res) =>{
  console.log('going to sparql … ' + req.query.eventSearchbar);
  let searchterm = req.query.eventSearchbar;
  let comment = 'not set';

  const endpointUrl = 'http://dbpedia.org/sparql';
  const query = `
  PREFIX res: <http://dbpedia.org/resource/>
  
  SELECT ?comment
  WHERE
  {
  res:${searchterm} rdfs:comment ?comment 
  FILTER(lang(?comment)="en")
  }`;

  console.log(query);
  const client = new SparqlClient({ endpointUrl });
  const stream = await client.query.select(query);
  
  stream.on('data', row => {
    Object.entries(row).forEach(([key, value]) => {
      comment = `${key}: ${value.value} (${value.termType})`;
      console.log(comment);
    });
  });

  stream.on('error', err => {
    console.error(err);
  });


  res.render('search',{searchterm: searchterm, wikiDescription: comment });
}

I would try running res.render('search',{searchterm: searchterm, wikiDescription: comment }); after the stream has ended and all data is written. Something like below. The way you have it right now that line runs right away, before (or while) the data is read.

stream.on('end', () => {
  res.render('search',{searchterm: searchterm, wikiDescription: comment });
}

This resource may be helpful with some examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM