• Promise 异步执行的同步操作


    Promise 是用来执行异步操作的。

    但有时一个异步操作需要等其他的异步操作完成,这时候就可以使用then来做。

     function loadImageAsync(url) {
            return new Promise(function(resolve, reject) {
                var image = new Image();
    
                image.onload = function() {
                    console.log("load");
                    resolve(image);
                };
    
                image.onerror = function() {
                    reject(new Error('Could not load image at ' + url));
                };
                console.log("change src");
                function init_img() {
                    image.src = url;
                }
                setTimeout(init_img,2000);
            });
        }

    loadImageAsync 用来异步加载图片. setTimeout 人为地延迟2秒加载

    function loadImageAsync2(url) {
            return new Promise(function(resolve, reject) {
                var image = new Image();
    
                image.onload = function() {
                    console.log("2load");
                    resolve(image);
                };
    
                image.onerror = function() {
                    reject(new Error('Could not load image at ' + url));
                };
                console.log("2change src");
                function init_img() {
                    image.src = url;
                }
                setTimeout(init_img,1000);
            });
        }
    loadImageAsync2 也是用来加载图片,人为地延迟1秒。

    var p = loadImageAsync('http://img02.tooopen.com/images/20141231/sy_78327074576.jpg');
        p.then(function (img) {
            console.log("1:"+img.src);
        });
        var h = loadImageAsync2('http://img02.tooopen.com/images/20141225/sy_77944235469.jpg');
        h.then(function (img) {
            console.log("2:"+img.src);
        });
    console.log("jjjjj");
     

    第一种调用方式,分别创建promise 实例 p 和 h。

    调用结果:


    可以看到 图片2先加载, 然后加载图片1 。

      var s = loadImageAsync('http://img02.tooopen.com/images/20141231/sy_78327074576.jpg');
        s.then(function (img) {
            console.log("1:"+img.src);
            return loadImageAsync2('http://img02.tooopen.com/images/20141225/sy_77944235469.jpg');
        }).then(function (img) {
            console.log("2:"+img.src);
        });

    创建新的promise 对象 s. 我们在s 的then 成功回调函数中 去调用 loadImageAsync2 函数。

    这样就保证了 加载图片2 之前先加载图片1. 

    这里注意的是第二个then 其实是loadImageAsync2 返回的promise 实例调用的。

    Promise相关学习链接:http://es6.ruanyifeng.com/#docs/promise

     
  • 相关阅读:
    postman的几个问题
    服了这个所谓北大青鸟官方学员社区论坛
    Gatling实战(三)
    Gatling实战(二)
    Gatling实战(一)
    httplib和urllib2常用方法
    jmeter的新增函数说明
    windows版jmeter的body data如何用 作为“换行”
    linux下oracle服务启动关闭
    linux下ORACLE监听日志的正确删除步骤
  • 原文地址:https://www.cnblogs.com/neverleave/p/6076624.html
Copyright © 2020-2023  润新知