ES6语法异步转同步

2018-12-17  本文已影响0人  全都是泡沫啦
<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>

    function getAjax(url){
        return new Promise((resolve,reject)=>{
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if(xhr.readyState === 4){
                    if(xhr.status===200){
                        let text = xhr.responseText;
                        let data = JSON.parse(text);
                        resolve(data);
                    }else{
                        reject("ajax请求发送失败");
                    }
                }
            };
            xhr.open("get",url);
            xhr.send();
        });
    }

    function getAjaxJquery(url){
        return $.ajax({url,async:true});
    }

    // getAjaxJquery("http://127.0.0.1:9000/test1").then(
    //     (data)=>{
    //         debugger
    //     } 
    // )
    // getAjax("http://127.0.0.1:9000/test1").then(
    //     (data)=>{
    //         debugger
    //     }
    // )

    async function test(){
        let data = await getAjaxJquery("http://127.0.0.1:9000/test1");
        console.log("1:"+data)
        let data2 = null;
        if(data.type == "test2"){
            console.log("2.1")
            data2 = await getAjaxJquery(`http://127.0.0.1:9000/test2`);
        }else if(data.type == "test3"){
            console.log("2.2")
            data2 = await getAjaxJquery(`http://127.0.0.1:9000/test3`);
        }
        
        console.log("2:"+data2)
        console.log("3")
    }
    // test()//test内部是同步,外层调用test()是异步
    // console.log("执行123")


    function *Test2(){
        console.log("=====1:")
        let data1 = yield getAjax("http://127.0.0.1:9000/test1");
        let data2 = null;
        if(data1.type == "test2"){
            console.log("=====2.1")
            data2 =  yield getAjax(`http://127.0.0.1:9000/test2`);
            console.log("=====2.1.1")
        }else if(data1.type == "test3"){
            console.log("=====2.2")
            data2 =  yield getAjax(`http://127.0.0.1:9000/test3`);
            console.log("=====2.2.2")
        }
        console.log("=====2:"+data2)
        return "=====123";
    }    
    if(false){
        let test2 = Test2();
        test2.next() //test2.next() = getAjax("http://127.0.0.1:9000/test1")
        .value.then(
            (data11) => {//data12为test1接口返回的数据
                let result = test2.next(data11); //data11:会传入到 *Test2中let data1 = data11
                                                //test2.next(data) = getAjax(`http://127.0.0.1:9000/test2`) 
                                                //test2.next(data) = getAjax(`http://127.0.0.1:9000/test3`)
                return result.value;
            },
            null
        ).then(
            (data22) => {//data22为接口test2或者test3的接口返回的数据
                let result  = test2.next(data22); //data22:会传入到 *Test2中let data2 = data22
                                                //result为*Test2的return
            console.log("result:"+result.value)
            }
            ,
            null
        )
    }
    
    

    function *Test3(){
        console.log("+++++1:")
        let data = yield getAjaxJquery("http://127.0.0.1:9000/test1");
        let data2 = null;
        if(data.type == "test2"){
            console.log("+++++2.1")
            data2 =  yield getAjaxJquery(`http://127.0.0.1:9000/test2`);
            console.log("+++++2.1.1")
        }else if(data.type == "test3"){
            console.log("+++++2.2")
            data2 =  yield getAjaxJquery(`http://127.0.0.1:9000/test3`);
            console.log("+++++2.2.2")
        }
        console.log("+++++2:"+data2)
        return "+++++123";
    }    
    
    let test3 = Test3();
    let z1 = test3.next();
    console.log("+++++z1:"+z1);
    z1.value.then(
        (data) => {
            return test3.next(data).value;
        }
    ).then(
        (data) => {
            let result = test3.next(data).value;
            console.log(result)
        }
    )
    console.log("end...")
</script>
</html>
package com.example.testweb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@RestController
public class TestwebApplication {

    @RequestMapping("/test1")
    public Map<String, Object> test1(){
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("type","test2");
        return objectObjectHashMap;
    }

    @RequestMapping("/test2")
    public Map<String, Object> test2(){
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("name","张三");
        objectObjectHashMap.put("age",18);
        return objectObjectHashMap;
    }

    @RequestMapping("/test3")
    public Map<String, Object> test3(){
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("name","李四");
        objectObjectHashMap.put("age",20);
        return objectObjectHashMap;
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new ApiOriginFilter());
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(1);
        return registration;
    }

    public static void main(String[] args) {
        SpringApplication.run(TestwebApplication.class, args);
    }

    public static class ApiOriginFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type");
            res.addHeader("Access-Control-Allow-Credentials", "true");
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读