【问题标题】:jquery - $.when() with single deferred and array of deferredjquery - $.when() 具有单个延迟和延迟数组
【发布时间】:2017-10-03 05:46:25
【问题描述】:

我正在使用 jquery 并且有两个变量。

trackFeatures - 单个 ajax 请求,artistRequests - ajax 请求数组

我想在 trackFeatures 和 artistRequests 都完成后做一些事情。对于艺术家请求,我可以这样做:

$.when.apply($, artistRequests).done(function() { ... }

有没有办法将单个请求与数组请求结合起来?除了将单个请求添加到数组或按顺序测试它们。

谢谢

【问题讨论】:

    标签: javascript jquery ajax asynchronous deferred


    【解决方案1】:

    引用此link 和示例:

    var d1 = $.Deferred();
    var d2 = $.Deferred();
     
    $.when( d1, d2 ).done(function ( v1, v2 ) {
        console.log( v1 ); // "Fish"
        console.log( v2 ); // "Pizza"
    });
     
    d1.resolve( "Fish" );
    d2.resolve( "Pizza" );

    类似地,如果你有类似artistRequests = [d1,d2] 的承诺数组

    您可以对数组使用扩展运算符,例如

    $.when(trackFeatures , ...artistRequests ).done(function ( v1, v2 ) {
        console.log( v1 ); // "Fish"
        console.log( v2 ); // "Pizza"
    });

    PS:...artistRequests 将数组的每个值拆分为单个变量。

    【讨论】:

    • 看起来我可以只使用 ...artistRequests 就好像它是它自己的参数一样,所以 $.when(trackFeatures, ...artistRequests).done(function() { 。 .. } 对我有用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2013-03-09
    • 2011-08-03
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多