我试图了解承诺,现在我很难过。 这是我的例子不起作用:
@if (Model == null)
{
@ViewData.ModelMetadata.NullDisplayText
}
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{
@ViewData.ModelMetadata.SimpleDisplayText
}
else
{
<dl class="dl-horizontal">
@foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
{
if(MvcHtmlString.IsNullOrEmpty(Html.Display(prop.PropertyName)))
{
continue;
}
if (prop.HideSurroundingHtml)
{
@Html.Display(prop.PropertyName)
}
else
{
<dt>@prop.GetDisplayName()</dt>
<dd>@Html.Display(prop.PropertyName)</dd>
}
}
</dl>
}
此警报&#34; 1&#34;然后&#34; 2&#34;那就是它。
为什么&#34; 3&#34;从未惊动过?为什么then()根本不执行?
答案 0 :(得分:3)
您需要解决承诺:
function doTheThing () {
return new Promise (function (resolve, reject) {
setTimeout(function(){
alert("2");
resolve();
}, 1000)
alert("1");
});
}
想象一下,如果你的代码采用了一个回调参数,而不是返回一个Promise:
function doTheThing (doneCallback) {
setTimeout(function(){
alert("2");
doneCallback();
}, 1000);
alert("1");
}
您需要调用doneCallback
将值传递给调用异步代码(或者只是让它知道它可以继续,就像在这种情况下一样)。解析(或拒绝)Promise类似于它 - 它启用异步流控制和值传递。
答案 1 :(得分:2)
承诺必须是resolved
或rejected
才能继续将执行传递给下一个then
成功或错误处理程序。因此,在doTheThing
功能中,您需要致电resolve
。我已经修改了你的代码,以证明通过调用resolve
你将控制权传递给成功处理程序,显而易见的是通过调用3
给出了值resolve("3")
。
function doTheThing () {
return new Promise (function (resolve, reject) {
setTimeout(function(){alert("2");},1000)
alert("1");
resolve("3");
});
}
doTheThing().then(function(value) {
alert(value);
}, function(error) {
alert("5");
});
答案 2 :(得分:0)