0.解析Promise和async
0.1箭头函数
es6中出现的函数形式
开发时根据实际情况可以省略一些东西
单条处理可以省略return和{大括号}
单个参数可以省略(小括号)
let fun = function(params){}
//可以缩写成如下 箭头函数会改变this的指向
let fun= params =>{}
//当参数有两个及以上时,如下:
let fun= (params1,params2,,,)=>{}
0.2语法糖举例
计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。
通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。
箭头函数,引用
// 新建一个util.js 文件夹
let formatTime = date=>{
....
}
let endTime = date=>{
....
}
module.exports = {
formatTime,
endTime,
}
//可以用import {名称} from '模块'
//然后再同级目录创建一个js文件 引入 util.js
//import {endTime} from 'util'
//或者全部引入
//import util from 'util'
0.3Promise和fetch()解析
//fetch是全局量window的一个方法,第一个参数为URL。
//使用fetch方法请求数据更加的简单,语法简洁,数据处理过程更加的清晰,基于Promise实现。
fetch('/some/url', { method: 'get', })
// 第一个then 设置请求的格式
.then(e => e.json())
// 第二个then 处理回调
.then((data) => {
<!-- data为真正数据 -->
}).catch(e => console.log("Oops, error", e))
//普通调用
$.get('/',function(data){console.log(data.length)})
//fetch
fetch('/').then(res=>res.text()).then(data=>console.log(data.length))
//promise --new Promise时里面的内容会立即执行,为了能实现调用时执行,一般Promise都作为函数的返回值
//resolve接受正确结果,导入then ,reject接受cuow导入catch
new Promise((res,rej)=>{
setTimeout(function(){res(123)},1000)
}).then(res=>console.log(res)).catch(e=>console.log(e))
new Promise((res,rej)=>{
setTimeout(function(){rej(123)},1000)
}).then(res=>console.log(res)).catch(e=>console.log(e))
1 then的传递性:promise().then(x=>y).then(z=>z) 这里第二个then的输入参数z就是上一个then返回值传递过来的y。
2 then传递时的变化: 如果上面y是个promise,则z是promise执行完只有的结果(resolve中的结果)!!!!
上面解释了fetch().then(res=>res.text()).then(data=>console.log(data))。这里面res.text()得到的是个promise,所以传到下一个then中的data会被’偷偷’解析成运行完的结果。
0.4Promise和async
var p1= () => new Promise((res,rej)=>setTimeout(()=> res(12345),1000)) //定义箭头函数p1,不传参返回Promise对象,
//async 和 await联合使用,await会拿到resolve结果是then函数的语法糖
async function q1(){
var res=await p1(); //可以同步编程避免回调地狱
console.log(res)
}
//等价的promise then形式
function q2(){
p1().then(res=>console.log(res))
}
- 同时打印await是promise和asyn的简写
0.5await解决回调
async function main(){
try{//统一的try catch
//async 和 await联合使用,await会拿到resolve结果是then函数的语法糖
var data1=await query(sql1)
var data2=await query(sql2)
var data3=await query(sql3)
}catch(e){
console.log(e)
}
}