我有一个函数( loadImageProfilePersonnel )创建并加载附加到DOM的图像元素,该函数返回一个promise。我还有另一个函数async函数( RenderHtmlPersonnel_Async ),该函数调用promise。但是,整个过程需要太多时间(2秒)才能将图像元素显示在屏幕上。如果有人可以告诉我下面的代码有哪些改进之处,我将不胜感激。
function loadImageProfilePersonnel(profile)
{
return new Promise(function (resolve, reject)
{
const campus = profile.ProfileId;
//const imageProfile = new Image();
const imageProfile = document.createElement('img');
if (profile.Picture !== '')
{
//imageProfile.src = '/Fundamental/ImageProfil/' + campus;
imageProfile.setAttribute('src', `/Fundamental/ImageProfil/${campus}`);
}
else
{
//imageProfile.src = '/Content/assets/img/DefaultImageUser.jpg';
imageProfile.setAttribute('src', '/Content/assets/img/DefaultImageUser.jpg');
}
imageProfile.onload = () => resolve(imageProfile);
imageProfile.onerror = () => reject(new Error('Unable to load image for profile: ' + profile));
const htmlMarkup =
`<div class="widget widget-chart">
<div class="widget-header bg-inverse-dark">
<h4 class="text-white">Informations du client</h4>
</div>
<div class="widget-body">
<div class="text-center m-b-30">
<img src="${imageProfile.src}" class="img-circle img-fluid" width="50" height="50">
</div>
<form class="form-horizontal" data-parsley-validate="true" name="demo-form">
<div class="form-group m-b-5">
<label class="col-md-6" for="Nom">Nom : </label>
<div class="col-md-6">
<p id="Nom">${profile.PropertyValue1}</p>
</div>
</div>
<div class="form-group m-b-5">
<label class="col-md-6" for="Prenom">Prénom : </label>
<div class="col-md-6">
<p id="Prenom">${profile.PropertyValue2}</p>
</div>
</div>
<div class="form-group m-b-5">
<label class="col-md-6" for="Type">Type : </label>
<div class="col-md-6">
<p id="Type">${profile.Type}</p>
</div>
</div>
<div class="form-group m-b-5">
<label class="col-md-6" for="SubCategory">Sous-Catégorie : </label>
<div class="col-md-6">
<p id="SubCategory">${profile.subCategory}</p>
</div>
</div>
<div class="form-group m-b-5">
<label class="col-md-6" for="Category">Catégorie : </label>
<div class="col-md-6">
<p id="Category">${profile.Category}</p>
</div>
</div>
</form>
</div>
</div>`;
$('.DetailsClientWifi').html(htmlMarkup);
$('.DetailsClientWifi').css('display', 'block');
});
}
async function RenderHtmlPersonnel_Async(profile)
{
const promise = loadImageProfilePersonnel(profile);
const result = await promise;
//console.log(result);
}
function AfficherUI(profileId)
{
$.ajax({
url: '/Observer/GetActiveClientsByFloor',
type: 'POST',
data: {
TypeId: '23-d'
}
success: function(response){
profile = JSON.parse(response);
if(profile.profileId === ProfileId){
RenderHtmlPersonnel_Async(profile);
}
}
});
}
答案 0 :(得分:0)
您创建了<img>
标签imageProfile
,并等待它的onload
事件来解决您的诺言,但是您从不插入imageProfile
文档(您没有做任何someElement.appendChild()
)。
这意味着从字面上来讲,永远要兑现承诺,因为onload
事件将永远不会发生。