从零开始 React Native (3) grenerator函数 控制流管理 Promise

前端之家收集整理的这篇文章主要介绍了从零开始 React Native (3) grenerator函数 控制流管理 Promise前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="generator_test.js"></script>
    <Meta charset="UTF-8">
    <style type="text/css"> progress { width: 160px; border: 1px solid #0064B4; background-color: #e6e6e6; color: #0064B4; } </style>
    <title>code3_Generator函数</title>

</head>
<body>

<progress max="100" value="5"></progress>
<div id="data">sdf</div>
<!--<input type="button" name="button" onclick="ajax()" value="ajax请求"/>-->
<input type="button" name="button" onclick="myAjax()" value="newAjax请求"/>
</body>
</html>

JS

/** * Created by liuml on 2017/4/20. */

/** * 下一步,必须调用遍历器对象的next方法,使得指针移向下一个状态。 * 也就是说,每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield语句(或return语句)为止。 */
//grenerator函数
//区别
//1.返回值function*
//2.yield
function* func() {
    yield "step1";
    console.log("step1");

    yield "step2";
    console.log("step2");

    // return "result";
}

let state = func();
state.next();
state.next();
state.next();
console.log(state.next());

// 案例 :
//功能 显示进度条 -> 请求数据 ->获取数据成功 隐藏进度条
//显示进度条
function showLoadingProgress() {
    //
    let progress = document.getElementsByTagName("progress")[0];
    //定时器
    let interval = setInterval(function () {
        progress.value += 10;
        if (progress.style.display === "none") {
            clearInterval(interval); //取消定时器
        }
        /*if (progress.value == 100) {//用这种方式的话就不用隐藏了 这里进度条满了后自动给隐藏 progress.style.display = "none"; clearInterval(interval); }*/
    },300);
}

//请求数据
function loadUIDataAsynch(callback) {

    //模拟网络延时
    setTimeout(function () {
        //拿到数据

        let datanode = document.getElementById("data");
        console.log(datanode);
        console.log(datanode.innerHTML);
        datanode.innerHTML = "模拟从服务器获得的数据.";
        //隐藏进度条;
        callback();

    },3000);

}

//隐藏进度条
function hideLoadingProgress() {
    var progress = document.getElementsByTagName("progress")[0];
    progress.style.display = "none";
}

//
function loadUiMain() {
    showLoadingProgress();
    loadUIDataAsynch(hideLoadingProgress);

}

//当页面加载完成之后 开始操作
window.onload = loadUiMain;


//使用 Generator 函数

//显示进度条
function showLoadingProgress() {
    //不断刷新进度条
    //DOM
    var progress = document.getElementsByTagName("progress")[0];
    //定时器,每隔400毫秒,进度累加
    var interval = setInterval(function () {
        progress.value += 10;
        if (progress.style.display === "none") {
            clearInterval(interval); //取消定时器
        }
    },400);
}

//获取数据
function loadUIDataAsynch() {

    //模拟网络延时
    setTimeout(function () {
        //拿到数据
        let datanode = document.getElementById("data");
        console.log(datanode);
        console.log(datanode.innerHTML);
        datanode.innerHTML = "模拟从服务器获得的数据.";
        //隐藏进度条
        loader.next();
    },3000);

}

//请求数据

function hideLoadingProgress() {
    var progress = document.getElementsByTagName("progress")[0];
    progress.style.display = "none";
}

//异步操作的同步化表达
function* loadUi() {
    //显示对话框
    showLoadingProgress();
    //加载数据
    yield loadUIDataAsynch();
    //隐藏对话框
    hideLoadingProgress();

}

var loader;

window.onload = function () {
    loader = loadUi();
    loader.next();
}


//next传参
//yield句本身没有返回值,或者说总是返回undefined
//next方法可以带一个参数,该参数就会被当作上一个yield语句的返回值

/** * Generator 函数从暂停状态到恢复运行,它的上下文状态(context)是不变的。通过next方法的参数, * 就有办法在 Generator 函数开始运行之后,继续向函数体内部注入值。 * 也就是说,可以在 Generator 函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为。 */
function* func2() {
    console.log("started");
    let r1 = yield;
    console.log(r1); //输出yield返回值
    let r2 = yield;
    console.log(r2);
}

let state = func2();
state.next();
state.next("a");
state.next();

//循环输出,通过传参,随时让循环重新开始
function* func3() {
    for (let i = 0; i < 5; i++) {
        let reset = yield i;
        console.log(reset);
        if (reset) i = -1;
        //console.log(i);
    }
}

let state = func3();
console.log(state.next());
console.log(state.next());
//通过next传参,让yield有返回值
console.log(state.next(true));
console.log(state.next());
console.log(state.next());


//按照流程执行
//step1(value1) -> step2(value2) -> step3(value3) -> step4(value4)

function step4(value3,callback) {
    var value4 = `step4_${value3}`;
    callback(value4);
}

function step3(value2,callback) {
    var value3 = `step3_${value2}`;
    callback(value3);
}

function step2(value1,callback) {
    var value2 = `step2_${value1}`;
    callback(value2);
}

function step1(callback) {
    var value1 = `step1_start `;
    callback(value1);
}


//回调嵌套
step1(function (value1) {
    step2(value1,function (value2) {
        step3(value2,function (value3) {
            step4(value3,function (value4) {
                console.log(value4);
            });
        });
    });
});


function step4(value3) {
    return `step4_${value3}`;
}

function step3(value2) {
    return `step3_${value2}`;
}

function step2(value1) {
    return `step2_${value1}`;
}

function step1() {
    return `step1_start `;
}

//控制流管理
function* stepFunc() {
    let value1;
    yield value1 = step1();
    let value2;
    yield value2 = step2(value1);
    let value3;
    yield value3 = step3(value2);
    let value4;
    yield value4 = step4(value3);
    console.log(value4);
}
//顺序执行
for (var i of stepFunc());


//Ajax请求网络,json数据
//请求成功:显示数据
//请求失败:抛出异常
//局部刷新8
function ajax() {
    console.log("点击了ajax按钮");
    url = "test.json";
    var request = new XMLHttpRequest();
    request.open("GET",url);
    request.onreadystatechange = handler;
    request.responseType = "json";//响应类型 json
    request.setRequestHeader("Accept","application/json");
    request.send();
    //回调
    function handler() {
        if (request.readyState !== 4) {

            return;
        }
        if (this.state == 200) {//请求成功 显示数据
            console.log(this.response.message);
        } else {
            throw new Error(this.statusText);
        }
    }

}

//
//Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大
//Ajax请求网络,json数据
//请求成功:显示数据
//请求失败:抛出异常
//局部刷新
//Promise对象的三种状态
//Pending(进行中)、Resolved(已完成,又称 Fulfilled)和Rejected(已失败)
function ajax(url) {

    var promise = new Promise(function (resolve,reject) {
        var request = new XMLHttpRequest();
        request.open("GET",url);
        request.onreadystatechange = handler;
        request.responseType = "json";
        request.setRequestHeader("Accept","application/json");
        request.send();

        function handler() {
            //4完成响应 解析完成
            if (this.readyState !== 4) {
                return;
            }

            if (this.state == 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        }

    });
    return promise;

}

function myAjax() {
    console.log(ajax('test.json'));
    ajax('test.json').then(
        //resolve 成功
        function (json) {
            console.log(json);
            alert(json);
        },function (e) {
            //rejedt 失败
            console.log(e.message + "失败");
            alert(e.message);
        }
        // json => json.message.log
        //reject 失败
    )


}
function ajax(url) {
    var promise = new Promise(function (resolve,url)
        request.onreadystatechange = handler;
        request.responseType = "json"; //服务器响应数据的类型 json
        request.setRequestHeader("Accept","application/json");
        request.send();

        //回调
        function handler() {
            //4(完成)响应内容解析完成
            if (this.readyState !== 4) {
                return;
            }
            if (this.status == 200) {
                //请求成功:显示数据
                resolve(this.response);
            }
            else {
                reject(new Error(this.statusText));
            }
        }
    });

    return promise;
}

//指定resolve状态、reject状态的回调函数
ajax('test.json').then(
    //resolve
    json => alert(json.message),//reject,可选的
    e => console.log(e.message)
);

还有个json 文件数据 我随便搞的
名字是test.json

{
  "repBody": { "appSignins": [ { "id": 41111,"user_id": 21733,"user_loginname": "测试内容ph34","count": 1,"create_time": 1482217201000,"last_logintime": 1482197775000,"remark": "第1天","score": 5,"user_apptype": "0" },{ "id": 41111,"count": 2,"create_time": 1482317353818,"remark": "连续签到第2天","score": 10,"count": 3,"create_time": 1482403753819,"last_logintime": 1482230953818,"remark": "签到第3天","count": 4,"create_time": 1482490153819,"last_logintime": 1482230953819,"remark": "签到第4天","count": 5,"create_time": 1482576553819,"remark": "签到第5天","count": 6,"create_time": 1482662953820,"remark": "签到第6天","count": 7,"create_time": 1482749353820,"last_logintime": 1482230953820,"remark": "连续签到第7天","score": 20,"count": 8,"create_time": 1482835753821,"remark": "签到第8天","count": 9,"create_time": 1482922153821,"last_logintime": 1482230953821,"remark": "签到第9天","count": 10,"create_time": 1483008553821,"remark": "签到第10天","count": 11,"create_time": 1483094953822,"remark": "签到第11天","count": 12,"create_time": 1483181353822,"last_logintime": 1482230953822,"remark": "签到第12天","count": 13,"create_time": 1483267753823,"remark": "签到第13天","count": 14,"create_time": 1483354153823,"last_logintime": 1482230953823,"remark": "连续签到第14天","score": 50,"count": 15,"create_time": 1483440553824,"remark": "签到第15天","count": 16,"create_time": 1483526953824,"last_logintime": 1482230953824,"remark": "签到第16天","count": 17,"create_time": 1483613353825,"remark": "签到第17天","count": 18,"create_time": 1483699753825,"remark": "签到第18天","count": 19,"create_time": 1483786153825,"last_logintime": 1482230953825,"remark": "签到第19天","count": 20,"create_time": 1483872553827,"remark": "签到第20天","count": 21,"create_time": 1483958953827,"last_logintime": 1482230953827,"remark": "签到第21天","count": 22,"create_time": 1484045353828,"remark": "签到第22天","count": 23,"create_time": 1484131753828,"last_logintime": 1482230953828,"remark": "签到第23天","count": 24,"create_time": 1484218153829,"remark": "签到第24天","count": 25,"create_time": 1484304553829,"last_logintime": 1482230953829,"remark": "签到第25天","count": 26,"create_time": 1484390953829,"remark": "签到第26天","count": 27,"create_time": 1484477353830,"remark": "签到第27天","count": 28,"create_time": 1484563753830,"last_logintime": 1482230953830,"remark": "签到第28天","count": 29,"create_time": 1484650153831,"remark": "签到第29天","count": 30,"create_time": 1484736553831,"last_logintime": 1482230953831,"remark": "连续签到第30天","score": 100,"user_apptype": "0" } ],"isSigned": false,"resCode": "1","resMsg": "获取数据成功!" } }

猜你在找的React相关文章