创建 jquery promise 层次结构的指南

Guidance for creating jquery promise hierarchy

本文关键字:层次结构 jquery promise 创建      更新时间:2023-09-26

我正在尝试延迟加载网站的一些资产。我对承诺很陌生,但在这种情况下,它们似乎非常有帮助。具体来说,我创建了以下方法来下载 HTML 和 CSS 文件,然后翻转一个 KnockoutJS 可观察量,指示该部分随后可用。该方法如下所示:

function delayDownloadAssets(sectionName) {
var htmlRequest = $.ajax({ url: 'http://www.example.com/' + sectionName + '.html' }),
cssRequest = $.ajax({ url: 'http://www.example.com/' + sectionName + '.css'  });
$.when(firstRequest, secondRequest).done(function (firstResponse, secondResponse) {
    //Insert HTML assets and CSS assets into DOM
    app.sections[sectionName].enabled(true);
});
}

然后,我可以像以下方式调用该方法几次:

delayDownloadAssets("Section1");
delayDownloadAssets("Section2");
delayDownloadAssets("Section3");

目前为止,一切都好。但我想以类似的方式包装所有三个部分的下载调用,以便我可以采取行动。像这样:

$.when(delayDownloadAssetsCall1, delayDownloadAssetsCall2,delayDownloadAssetsCall3).done(function () {
    alert('Web site download is entirely complete!');
});

我希望这个问题是明确的,但如果需要澄清,请告诉我。谢谢!

如果你只返回 $.when 结果,它应该按原样工作:

function delayDownloadAssets(sectionName) {
    var htmlRequest = $.ajax({ url: 'http://www.example.com/' + sectionName + '.html' }),
        cssRequest = $.ajax({ url: 'http://www.example.com/' + sectionName + '.css'  });
    //add return here
    return $.when(firstRequest, secondRequest).done(function (firstResponse, secondResponse) {
        //Insert HTML assets and CSS assets into DOM
        app.sections[sectionName].enabled(true);
    });
}

按照 Esailija 的指示编写delayDownloadAssets,您可以更进一步:

function loadSections(sections) {
    return $.when.apply(null, sections.map(delayDownloadAssets));
}

调用如下:

var sections = ["Section1", "Section2", "Section3"];
loadSections(sections).then(function() {
    //Web site download is entirely complete!
});

为什么不直接将 3 与 done 函数链接起来。

即第一次调用的 done 函数调用第二次,第二次调用的 done 函数调用

第三次,最后在第三次调用的 done 函数中做任何你想做的事情。

更新:

要在 Paralael 中运行,您需要异步代码。
首先创建一个全局

var doneFlag = 0; 

然后,我将使用 setTimeout 调用每个函数,该函数仅包含

doneFlag++;

然后是调用简单循环的第四个 setTimeout 函数

while(doneFlag != 3)
{
   var x = 5+5; //just to keep from crashing js 
}
//any code you want to run after complete dl of all.