如何从简单的jsdom函数返回值?

我使用jQuery与jQuery,它工作得很好。 然而,我试图模块化我的代码,所以我不重复自己,所以我做了一些基本的function,从一些HTML(DOM)的jsdom代码,调整它与jQuery,并吐出来。 但是,我无法返回我的结果,因此将其分配给调用var。 我可能不是在正确的地方回来,但我只是没有看到明显的,如果是的话。 可以使用一点帮助。

代码如下:

function tweakIt(html_in){ var jsdom = require('jsdom'); jsdom.env({ html: html_in, scripts: [ '../public/javascripts/jquery-1.7.1.min.js', ], done: function(errors, window) { var $ = window.$; // do some jquery magic and manipulate the dom $('body').append('<div>foo</div>'); console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly return $('body').html(); // this isn't returned to where I called tweakIt() from, why not? } }); } var oldhtml = '<html><body><div>some text</div></body></html>'; var newhtml = tweakIt(oldhtml); // never gets set because nothing gets returned, why? 

编辑:

这确实是一个asynchronous的问题,所以这里是如何使用callback而不是返回来完成的:

 function tweakIt(html_in, callback){ var jsdom = require('jsdom'); jsdom.env({ html: html_in, scripts: [ '../public/javascripts/jquery-1.7.1.min.js', ], done: function(errors, window) { var $ = window.$; // do some jquery magic and manipulate the dom $('body').append('<div>foo</div>'); console.log('Freshly Manipulated HTML: '+ $('body').html()); // it logs perfectly callback($('body').html()); // instead of a return, pass the results to the callback } }); } var oldhtml = '<html><body><div>some text</div></body></html>'; var newhtml = tweakIt(oldhtml, function(newstuff){ console.log(newstuff); // woohoo! it works! }); 

我不认为你可以做这个使用返回值,因为done:是一个asynchronous函数。 尝试添加一个callback到你的tweakIt并获取新的HTML作为参数发送,例如

tweakIt(oldHtml, function(newHtml) {/*use the result here*/})

新版本的JSDOM API不再包含“完成”callback选项。

所以我写了一个“穷人的callback”来访问一个DOMvariables,只有在它被设置后。

 function getSomeDOMVar(callback) { const jsdom = require("jsdom"); const { JSDOM } = jsdom; const dom = new JSDOM(` <!DOCTYPE html> <html> <body> <script> var result; // globally scoped, undefined var, accessible in the node scope as dom.window.result function doSomething() { // your code goes here } // then assign the data you want back to your the globally scoped var result = doSomething(); </script> </body> </html> `, { runScripts: "dangerously", resources: "usable" }); // poor man's callback function waitForVar() { if (typeof dom.window.result !== 'undefined') { cb(dom.window.result); } } setTimeout(waitForVar, 1000); } getSomeDOMVar(function(result) { console.log(result) });