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

k00*_*00k 5 node.js express jsdom

我正在使用带有jquery的jsdom,它工作得很好.但是,我正在尝试模块化我的代码,所以我不重复自己,所以我用一些jsdom代码创建了一个基本函数,它接受了一些html(DOM),用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?
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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!
});
Run Code Online (Sandbox Code Playgroud)

Bij*_*lle 5

我不认为你可以使用返回值来做到这一点,因为done:是一个异步函数.尝试向tweakIt添加一个回调,并通过将其作为参数发送来获取新的html,例如

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