无法在Javascript中传递variables

我试图用node.js从word文档中抓取数据。

我目前的问题是,下面的控制台日志将作为适当的variables返回果汁块内的值。 如果我把它移到果汁块外面,它会完全丢失。 我试图把回报

function getMargin(id, content){ var newMargin = content.css("margin-left"); if(newMargin === undefined){ var htmlOfTarget = content.toString(), whereToCut = theRaw.indexOf("<div class=WordSection1>"); fs.writeFile("bin/temp/temp_" + id + ".htm", theRaw.slice(0, whereToCut) + htmlOfTarget + "</body> </html>", function (err){ if (err) { throw err; } }); juice("bin/temp/temp_" + id + ".htm", function (err, html) { if (err) { throw err; } var innerLoad = cheerio.load(html); newMargin = innerLoad("p").css("margin-left"); console.log(newMargin); // THIS newMargin AS VALUE }); } console.log(newMargin);//THIS RETURNS newMargin UNDEFINED return newMargin; } 

我认为问题在于fs.write和juice是Asyc的function。 我只是不知道如何解决这个问题。 我必须能够按顺序调用getMargin。

正如在评论中提到的,在asynchronous代码完成后,将程序stream更改为在callback中运行。

 // accept callback as parameter, and run it after async methods complete... function getMargin(id, content, callback){ var newMargin = content.css("margin-left"); if(newMargin === undefined){ var htmlOfTarget = content.toString(), whereToCut = theRaw.indexOf("<div class=WordSection1>"); fs.writeFile("bin/temp/temp_" + id + ".htm", theRaw.slice(0, whereToCut) + htmlOfTarget + "</body> </html>", function (err){ if (err) { throw err; } // move the juice call inside the callback of the file write operation juice("bin/temp/temp_" + id + ".htm", function (err, html) { if (err) { throw err; } var innerLoad = cheerio.load(html); newMargin = innerLoad("p").css("margin-left"); console.log(newMargin); // THIS newMargin AS VALUE // now run the callback passed in the beginning... callback(); }); }); } } // call getMargin with callback to run once complete... getMargin("myId", "myContent", function(){ // continue program execution in here.... });