【发布时间】:2019-04-01 01:59:46
【问题描述】:
我正在尝试使用 Promises 一个接一个地运行一些函数,但不知何故,第二个函数要么在第一个函数之前执行,要么根本不执行。 情况是这样的:
我有以下功能:
- 从部分文件夹加载可重用的 html 代码:
function insertingPartials() {
return new Promise( function(resolve,reject) {
$('#navbar-placeholder').load('/Assets/Partials/navbar.html');
$('#jumbotron-placeholder').load('/Assets/Partials/jumbotron.html');
$('#footer-placeholder').load('/Assets/Partials/footer.html');
resolve();
reject('Error');
});
- 进行语言调整的工具
function languageSpecifics() {
return new Promise( function(resolve,reject) {
//showing correct text per html language
$('span[lang=' + $('html')[0].lang + ']').show();
$('div[lang=' + $('html')[0].lang + ']').show();
//disabling the current language from the language selection menu
$('a[lang=' + $('html')[0].lang + ']').addClass('disabled');
//links dynamically point to the correct sub-pages
$('.blog-link').attr('href', '/' + $('html')[0].lang + '/Blog/');
$('.prod-link').attr('href', '/' + $('html')[0].lang + '/' + $('.prod-link span[lang=' + $('html')[0].lang + ']').text() + '/');
$('#en').attr('href', window.location.href.replace($('html')[0].lang, 'en'));
$('#es').attr('href', window.location.href.replace($('html')[0].lang, 'es'));
$('#ro').attr('href', window.location.href.replace($('html')[0].lang, 'ro'));
resolve();
reject('Error in ' + arguments.callee.name);
});
}
- 将内容滑入视图:
function loadContent() {
return new Promise( function(resolve,reject) {
//fading content in
$('nav').animate({top: '0'});
$('footer').animate({bottom: '0'});
$('.main-content').animate({right: '0'}).css('overflow', 'auto');
//fading preloading out
$('.spinner-border').fadeOut();
$('#preloading').removeClass('d-flex').addClass('d-none');
resolve();
reject('Error in ' + arguments.callee.name);
});
}
- 和一个调整容器高度的工具
function setContainerHeight() {
//setting the height of the container
$('.container').css('height', $('body').height() - ($('nav').height() + $('footer').height()) + 'px');
}
我要做的是让函数按照我将它们放在上面的顺序执行。下面的代码输出 1,2,3,4 但函数“languageSpecifics”未执行或在“insertingPartials”之前执行,因为加载了部分,然后组件滑入视图,但看不到文本,也看不到链接指向任何地方。
$(document).ready( function() {
console.log('1')
insertingPartials().then( function() {
console.log('2');
languageSpecifics().then( function() {
console.log('3');
loadContent().then( function() {
console.log('4');
setContainerHeight();
});
});
});
});
如果我在浏览器控制台中单独执行这些函数,我会得到所需的输出,并且每个承诺都会返回。如果我使用 .then() 运行它们,则承诺返回待处理并且我没有在页面上看到任何文本。 (嵌套的“.then(.then()”)和同一级别的“.then().then()”给出相同的结果)
我想知道我在这里做错了什么。 另外,如果有更好/更有效的方法来实现我在这里尝试做的事情,请提出建议。
【问题讨论】:
-
您是否需要完成所有 3 个
load()才能执行其他操作,或者您是否可以在每个load()完成后加载特定内容? -
第一个大问题是
load()是异步的。因此,在insertingPartials()中,您在 3 次加载完成之前调用 resolve()。 -
也不明白为什么除了动画服务器端什么都不做
-
如何在服务器端执行所有操作? @charlietfl 你能在这里指出我正确的方向吗?这是一个简单的前端站点,我在本地使用 node http-server 进行测试。
-
好的,但是
lang的<html>是已知的,然后不知道吗?
标签: javascript jquery html promise