我正在使用 Promises 编写第一段代码,并得到了一些意想不到的结果。我有一些看起来像这样的代码(使用 jQuery):
$('.loading-spinner').show();
$('.elements').replaceWith(function() {
// Blocking code to generate and return a replacement element
});
$('.newElements').blockingFunction();
$('.loading-spinner').hide();
为了防止页面在运行此代码时被阻止,我尝试使用 setTimeout 和 Promises 使其异步,如下所示:
$('.loading-spinner').show();
var promises = [];
var promises2 = [];
$('.elements').each(function(i, el){
promises[i] = new Promise(function(resolve, reject) {
setTimeout(function() {
$(el).replaceWith(function() {
// Code to generate and return a replacement element
});
resolve(true);
}, 100);
});
});
Promise.all(promises).then(function(values) {
$('.newElements').each(function(i, el) {
promises2[i] = new Promise(function(resolve, reject) {
setTimeout(function() {
$(el).blockingFunction();
resolve(true);
}, 100);
});
});
});
Promise.all(promises2).then(function(values) {
$('.loading-spinner').hide();
});
我想要实现的是,一旦承诺promises
已解决,承诺promises2
被实例化。一旦这些问题得到解决,加载微调器就会被隐藏。
我得到的效果是,虽然页面没有被阻塞那么长时间,但一旦设置了所有 Promise,微调器就会消失,而不是等到它们得到解决。
我可以看到promises2
直到一切都完成后,承诺才会得到解决promises
已解决,所以我不明白为什么会发生这种情况。我想这要么是我没有正确理解 Promise,要么是没有低估使代码异步。