How can I Interleave / merge async iterables?

后端 未结 5 1304
抹茶落季
抹茶落季 2020-12-15 06:51

Suppose I have some asnyc iterable objects like this:

// Promisified sleep function
const sleep = ms => new Promise((resolve, reject) => {
  setTimeou         


        
5条回答
  •  旧时难觅i
    2020-12-15 07:24

    I hope I understood your question correctly, here's how I'd approach it:

    let results = [];
    
    Promise.all([ a, b, c ].map(async function(source) {
        for await (let item of source) {
            results.push(item);
        }
    }))
    .then(() => console.log(results));
    

    I tried it with three normal arrays:

    var a = [ 1, 2, 3 ];
    var b = [ 4, 5, 6 ];
    var c = [ 7, 8, 9 ];
    

    And it resulted in [1, 4, 7, 2, 5, 8, 3, 6, 9].

提交回复
热议问题