---
title: "异步并行串行编程 when"
author: "highfly-s"
date: "2014-11-14T11:40:44Z"
tags: []
categories: ["Web前端"]
slug: "when"
draft: false
lastmod: "2014-11-14T11:40:44Z"
id: 2155964
url: "https://highfly-s.iteye.com/blog/2155964"
---

var data = {

"51": \[{name:"a"},{name:"a1"}]

,"zhaoping": \[{name:"b"}]

,"xxx": \[{name:"c"}]

};

 

var groups = \[];

for(var x in data){

var def = new $.Deferred;

 

var accounts =  data\[x];

 

var accountsDef = \[];

 

 

var initDef = new $.Deferred;

var pipeDef = initDef;

 

 

for (var i = 0; i &lt; accounts.length; i++) {

(function(){

var account = accounts\[i];

var site = x;

 

var d = new $.Deferred;

pipeDef.done(function(){

setTimeout(function(){

console.log('one account done: ' + account.name);

d.resolve(site);

}, 1000)

})

pipeDef = d;

accountsDef.push(d);

})()

};

 

(function(){

var innerDef = def;

$.when.apply($, accountsDef).done(function() {

console.log('one group done: ' + arguments\[0]);

 

innerDef.resolve();

})

})()

 

 

 

initDef.resolve();

 

groups.push(def);

}

 

 

$.when.apply($, groups).done(function() {

console.log('all accounts finished');

})