zoukankan      html  css  js  c++  java
  • JavaScript 异步操作

    
    

    串行执行

    var items = [];
    for (var i=0;i<10000;i++){
        items[i]=i+1;
    }
    console.log(items);
    var results = [];
    
    function async(arg, callback) {
        console.log('参数为 ' + arg +' , 1秒后返回结果');
        setTimeout(function () { callback(arg * 2); }, 1000);
    }
    
    function final(value) {
        console.log('完成: ', value);
    }
    
    function series(item) {
        console.log(item)
        if(item) {
            async( item, function(result) {
                results.push(result);
                return series(items.shift());
            });
        } else {
            return final(results[results.length - 1]);
        }
    }
    
    series(items.shift());



    并行执行

    var items = [];
    for (var i=0;i<10000;i++){
        items[i]=i;
    }
    var results = [];
    
    function async(arg, callback) {
        console.log('参数为 ' + arg +' , 1秒后返回结果');
        setTimeout(function () { callback(arg * 2); }, 1000);
    }
    
    function final(value) {
        console.log('完成: ', value);
    }
    
    items.forEach(function(item) {
        async(item, function(result){
            results.push(result);
            if(results.length === items.length) {
                final(results[results.length - 1]);
            }
        })
    });

    并行与串行的结合

    <div id="app"></div>
    var items = [];
    for (var i=0;i<1000;i++){
        items[i] = i;
    }
    var results = [];
    var running = 0;
    var limit = 100;
    
    function async(arg, callback) {
        console.log('参数为 ' + arg +' , 1秒后返回结果');
        $("#app").append('<div>参数为 '+ arg +' , 1秒后返回结果</div>')
        window.scrollTo(0,document.body.scrollHeight);
        setTimeout(function () { callback(arg * 2); }, 3000);
    }
    
    function final(value) {
        console.log('完成: ', value);
        $("#app").append('<div>完成 '+ value.toString() +'</div>')
    }
    
    function launcher() {
        while(running < limit && items.length > 0) {
            var item = items.shift();
            async(item, function(result) {
                results.push(result);
                running--;
                if(items.length > 0) {
                    launcher();
                } else if(running == 0) {
                    final(results);
                }
            });
            running++;
        }
        console.log("当前执行任务数量:"+running+" 剩余任务数量:"+items.length);
    }
    launcher();
  • 相关阅读:
    Scan image with TWAIN scanner and insert into Rich Text (R5/Win32)
    软件测试工具汇总
    domino升级602>651
    domino SMTP验证LDAPPOP3的实现
    domino升级602>651>851
    DOMINO中的内置域
    Attaching and importing image files in one click
    传西门子中国运营中近一半业务涉及行贿 沧海
    IT程序员:如何化蛹为蝶? 沧海
    年度个人职业规划秘笈 沧海
  • 原文地址:https://www.cnblogs.com/chenwh/p/9848454.html
Copyright © 2011-2022 走看看