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和结束;
  • 相关阅读:
    谷粒商城所学知识点整理总结
    谷粒商城项目介绍
    JVM 中的垃圾回收
    对象的创建和分配
    JVM 中的异常
    JVM 中的StringTable
    一个 java 文件的执行过程详解
    复制表的方法
    从 Vue parseHTML 来学习正则表达式
    Visual Studio 2022 预览版下载来了(x64位)
  • 原文地址:https://www.cnblogs.com/GJcaowei/p/7207891.html
Copyright © 2011-2022 走看看