【发布时间】:2019-10-10 06:24:30
【问题描述】:
我有一个函数 (loadImageProfilePersonnel) 创建并加载附加到 DOM 的图像元素,该函数返回一个承诺。我还有另一个调用 promise 的函数异步函数 (RenderHtmlPersonnel_Async)。然而,整个过程需要太多时间(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);
}
}
});
}
【问题讨论】:
-
POST 需要多长时间?如果那是“慢点”,那么这里的代码就无所谓了。
-
如何查看 POST 需要多长时间?
-
一般您可以在 chrome 开发者工具的“网络标签”中看到响应时间。 @Xris
-
你最好先克隆 htmlMarkup,然后使用带有 JS document.querySelector 的 const 而不是 jQuery
-
你最好克隆这个元素,它已经可以为你节省很多时间了。
标签: javascript async-await es6-promise