javascript - Issues about the concurrency of generator functions in js that you don't know
为情所困
为情所困 2017-06-12 09:31:03
0
2
608

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

为情所困
为情所困

reply all(2)
巴扎黑

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_u1582

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!