zoukankan      html  css  js  c++  java
  • async 函数

    同步
    console.log(1);
    console.log(2);
    console.log(3);
    console.log(4);

    		//异步 ajax 文件读取io操作
    		console.log(1);
    		console.log(2);
    		setTimeout(function(){
    			console.log(3000);
    		},3000);
    		console.log(3);
    		console.log(4);
    		//先打印1 2 3 4,隔三秒后打印3000;
    		
    		//async函数返回的是resolve状态的Promise对象
    		async function fn(){
    			return "abc";
    		}
    		let result=fn();
    		console.log(result);//打印:Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "abc"}。*/
    

    Promise 对象

    		let p = new Promise(function(resolve,reject){
    			resolve("abc");
    		});
    		
    		p.then(function(data){
    			console.log(data);//打印abc。
    		});
    		//async函数里面的返回值传递给then方法
    		async function fn(){
    			return "123";
    		}
    		let p1 = fn();
    		p1.then(function(data){
    			console.log(data);//打印123.
    		});
    		
    		//async函数用来处理异步
    		
    		function one(){
    			return new Promise(function(resolve,reject){
    				setTimeout(function(){
    				console.log("one_3000");
    				resolve("one_3000");
    				},3000);
    			})
    			
    		}
    

    		function two(){
    			return new Promise(function(resolve,reject){
    				setTimeout(function(){
    				console.log("two_2000");
    				resolve("two_2000");
    				},2000);
    			})
    			
    		}
    		
    		//await只能出现在异步函数里面, 
    		async function shunxu(){
    			console.log("start");
    			let r1 = await one();
    			console.log(r1);
    			let r2 = await two();
    			console.log(r2);
    			return "end";
    		}
    		let p3 = shunxu();
    		p3.then(r=>{
    			console.log("结束");
    		});
    		
    		//先打印start,三秒后打印两次one_3000,打印完one_3000然后隔两秒打印两次two_2000和结束;
  • 相关阅读:
    Dubbo支持的协议的详解
    db2 SQL6036N解决办法
    9-5 HTTP注解演示及注意事项讲解
    9-4 Feign之HTTP注解介绍
    9-3 Feign演示及Feign注解解析
    9-2 Feign环境准备
    9-1 Feign自我介绍
    8-30 Hystrix章节总结
    8-29 实战技巧:如何设置线程池
    8-28 Hystrix监控讲解与演示
  • 原文地址:https://www.cnblogs.com/GJcaowei/p/7207891.html
Copyright © 2011-2022 走看看