异步流程控制

异步流程控制是javascript无法回避的问题
同步是一个任务执行完后在执行下一个任务,异步是指多个任务同时执行,因此如果有B任务需要任务A的结果就涉及到了异步流程控制的问题


回调函数
这是异步编程最基本的方法

function f1(callback) {
        console.log('start to run f1.');
        setTimeout(function () {
            console.log('f1 is finished. callback f2');
            callback();
        },3000);
    }
    function f2() {
        console.log('start to run f2.');
    }
    f1(f2);


运行结果
start to run f1.
f1 is finished. callback f2
start to run f2.

Promise
Promise对象是ES6新的规范,每一个异步任务返回一个Promise对象,该对象有一个then方法,允许指定回调函数

var getTestJson = function (url) {
        var promise = new Promise(function(resolve,reject){
            var xhr = new XMLHttpRequest();
            xhr.open("GET",url,true);
            xhr.onreadystatechange = function () {
                console.log("this.readyState:"+this.readyState+",this.status:"+this.status);
                if(this.readyState !== 4) {
                    return;
                }
                if(this.status === 200){
                    resolve(this.response);
                } else {
                    reject(new Error(this.statusText));
                }
            }
            xhr.responseType = "json";
            xhr.setRequestHeader("Accept","application/json");
            xhr.send();
        });
        return promise;
    };
    var url = "http://localhost:8000/getJson";
    getTestJson(url).then(function (json) {
        console.log('get the data back',json);
    },function (error) {
        console.log('error',error);
    });


getTestJson是一个异步任务,在任务执行结束后会调用.then方法
http://localhost:8000/getJson该地址是我在本地用nodejs搭的后台

猜你喜欢

转载自yilianxinyuan.iteye.com/blog/2373601