简体   繁体   English

如何等待 sparql 请求并在 nodejs 应用程序中设置变量?

[英]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.我是 sparql 和 nodejs 的新手,想查询 dbpedia 以设置变量并将其传递给前端。 However if I run my code I can console.log the requested data but I don't get it over to the frontend.但是,如果我运行我的代码,我可以 console.log 请求的数据,但我不会把它交给前端。 I m using the sparql-http-client js.我正在使用 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 });我会尝试运行res.render('search',{searchterm: searchterm, wikiDescription: comment }); after the stream has ended and all data is written.在 stream 结束并写入所有数据后。 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.资源可能对一些示例有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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