我正在尝试在我的Web应用程序中创建一个模型(MV中的M)来理解这个概念。我正在努力解决下面代码中出现的异步问题:
string unitsMap[] = { "zero", "one", "two", "three", "four", "five","six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string tensMap[] = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(abs(number));
string words = "";
if ((number / 1000000000) > 0)
{
words += NumberToWords(number / 1000000000) + " billion ";
number %= 1000000000;
}
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
我知道这是错误的,因为console.log将在getJSON完成之前发生,因为这是异步的。我应该如何设计这个来防止这个问题?
我认为获取前端MVC的实际数据是从模型中从等于我的RESTapi访问它。是否有一个首选的解决方案而不是像我一样在模型中执行此操作?
答案 0 :(得分:1)
您可以发送回调函数并在完成异步代码后执行它:
try
{
string htmlContent = TextBox1.Text.Replace("\r", "\n").Replace("\n", "");// you html code (for example table from your page)
Document doc = new Document();
string FileName = Guid.NewGuid().ToString();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("C:\\Nikhil Shah\\Projects\\Local Projects\\PracticeDemo\\PracticeDemo\\PDF\\" + FileName + ".pdf", FileMode.Create));
doc.Open();
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath(@"~\Content\myCss.css"), FileMode.Open));
cssResolver.AddCss(cssFile);
CssAppliers ca = new CssAppliersImpl();
HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// PIPELINES
PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
StringReader sr = new StringReader(htmlContent);
p.Parse(sr);
doc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".pdf");
Response.TransmitFile(Server.MapPath(@"~\PDF\" + FileName + ".pdf"));
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
答案 1 :(得分:1)
为了避免这个问题,您可以执行以下操作(因为从jQuery 1.5
.getJSON
实现了Promise
接口)
function FruitModel(api) {
this._api = api;
}
FruitModel.prototype = {
getFruit: function(fruit_id) {
return $.getJSON(this._api + fruit_id);
}
}
//Call
fruits.getFruit(123).done(function(data){
console.log(data);
})