Node.js 无法在nodejs和express中同步运行函数
我用过这个项目。这是我的Node.js 无法在nodejs和express中同步运行函数,node.js,express,asynchronous,mean,node-deasync,Node.js,Express,Asynchronous,Mean,Node Deasync,我用过这个项目。这是我的summary.js文件的代码 var wikipedia = require("wikipedia-js"); var something = "initial"; module.exports = { wikitext: function(topicname) { console.log("Inside wikitex funciton :" + topicname); var options = { q
summary.js
文件的代码
var wikipedia = require("wikipedia-js");
var something = "initial";
module.exports = {
wikitext: function(topicname) {
console.log("Inside wikitex funciton :" + topicname);
var options = {
query: topicname,
format: "html",
summaryOnly: false,
lang: "en"
};
wikipedia.searchArticle(options, function(err, htmlWikiText) {
console.log("Inside seararticlefunciton :");
if (err) {
console.log("An error occurred[query=%s, error=%s]", topicname, err);
return;
}
console.log("Query successful[query=%s, html-formatted-wiki-text=%s]", topicname, htmlWikiText);
something = htmlWikiText;
});
return something;
},
};
我在/wiki/:topicname
路线中使用的此模块。index.js
中对应的代码如下所示
router.get('/wiki/:topicname', function(req, res, next) {
var topicname = req.params.topicname;
console.log(topicname);
var first = summary.wikitext(topicname);
res.send("Hello "+first);
});
问题是,每次我访问wiki/某个主题时,summary.js
的最后一个返回语句都会在htmlWikiText
填充内容之前执行。所以我总是在浏览器页面上看到hello initial
。虽然经过一段时间后,由于console.log
语句,它会被打印到终端上
那么我应该如何解决这个问题呢?我不打算尝试将此代码转换为同步代码。我只是将其更正为异步版本 您需要将回调传递给wikitext(),并返回该回调中的值。以下是wikitext()的修订代码和调用它的路径:
var wikipedia = require("wikipedia-js");
module.exports = {
wikitext: function(topicname, callback) {
console.log("Inside wikitex funciton :" + topicname);
var options = {
query: topicname,
format: "html",
summaryOnly: false,
lang: "en"
};
wikipedia.searchArticle(options, function(err, htmlWikiText) {
console.log("Inside seararticlefunciton :");
if (err) {
console.log("An error occurred[query=%s, error=%s]", topicname, err);
return callback(err);
}
console.log("Query successful[query=%s, html-formatted-wiki-text=%s]", topicname, htmlWikiText);
callback(null, htmlWikiText);
});
}
};
router.get('/wiki/:topicname', function(req, res, next) {
var topicname = req.params.topicname;
console.log(topicname);
summary.wikitext(topicname, function(err, result) {
if (err) {
return res.send(err);
}
if (!result) {
return res.send('No article found');
}
res.send("Hello "+result);
});
});
很可能无法使其同步,请阅读
维基百科
的文档以确定答案。无论如何,在您的情况下,使其同步是一个可怕的想法,因为它将锁定您的服务器一段时间,使其无法响应任何请求。因此,如何仅在上述函数完成执行后返回值?文档中也没有提到同步或异步。你不能,那是不可能的。您必须使用回调。好的。我尝试在wikipedia.searchArticle函数中使用回调,但不起作用。应该如何在该函数中使用回调?为了成功地使用NodeJ,您需要了解回调。阅读github.com/maxogden/art of node#callbacks之类的文章,您将能够回答自己的问题。