I saw such code in a book. The purpose of the code is to initiate two asynchronous ajax requests at the same time and push the results into an array in order
//假设request是基于primose的ajax工具
var arr = [];
function *reqData ( url ) {
var data = yield request(url);
yield; //关于这一行书上是这样解释的,控制转移
arr.push(data);
}
var it1 = reqData("http:....1"), it2 = reqData("http:....2"); //总之是2个不同的url地址
var p1 = it1.next(), p2 = it2.next();
p1.then( function(data) {
it1.next(data);
} );
p2.then( function(data) {
it2.next(data);
} );
Promise.all([p1, p2]).then( function () {
it1.next();
it2.next();
} );
I have never understood what control transfer is used for, and the book doesn’t say much about it
var arr = [];
function *reqData ( url ) {
arr.push( yield request(url) );
};
var it1 = reqData("http:....1"), it2 = reqData("http:....2"); //总之是2个不同的url地址
var p1 = it1.next(), p2 = it2.next();
Promise.all([p1, p2]).then( data => {
var [data1, data2] = data;
it1.next(data1);
it2.next(data2);
});
This is my simplified code, removing the control transfer. What are the hidden dangers of doing this compared to the original one
巴扎黑2017-06-12 09:33:03
Personally, I think the reason why the code in the book is so verbose is just to ensure the order of getting the data array.
On the contrary, your simplified code is very elegant, simple and clean. . .
phpcn_u15822017-06-12 09:33:03
That is, after obtaining the data, the generator is paused again, waiting for uniform recording to the array, and controlling the order of writing to the array.
The code in your rewritten version of Promise.all is useless.