目录
- 1.Es6常见语法的使用
- 2.Async、Await和Promise
1.Es6常见语法的使用
1.let
、const
let
:是一个块作用域
if (true) { | |
let a = 123; | |
} | |
console.log(a); // a is not defined |
const
:定义常量
const PI = 3.1415926; | |
PI = 3.15 // Assignment to constant variable. | |
console.log(PI) |
var
:全局变量
2.箭头函数
setTimeout(() => { | |
console.log("我被执行了") | |
}, 1000) |
3.对象、属性和方法的简写
const name = "王五" | |
var person = { | |
// "name": name | |
// name: name | |
name | |
} | |
console.log(person.name) | |
var name = "候七" | |
var app = { | |
name, | |
// run: function(){ | |
// console.log(`${this.name}在跑步`) | |
// }, | |
run(){ | |
console.log(`${name}在跑步`) | |
} | |
} | |
app.run() |
4.模板字符串
const name = "张三" | |
const age = 27 | |
console.log(`${name}的年龄是${age}`) |
5.Promise
主要用来处理异步,比如下面的示例
function getData(){ | |
// 异步 | |
setTimeout(function(){ | |
let name = "孙悟空"; | |
return name | |
}, 1000) | |
} | |
console.log(getData()) // undefined |
如果要在外面获取异步对象执行的结果,可以使用callback
回调方式
function getData(callback){ | |
setTimeout(function(){ | |
let name = "孙悟空"; | |
callback(name); | |
}, 1000) | |
} | |
getData(function(result){ | |
console.log(result) // 孙悟空 | |
}) | |
Es6
中新特性Promise
方法
var p = new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
let name = "猪八戒"; | |
resolve(name) | |
}, 1000); | |
}) | |
p.then(function(data){ | |
console.log(data); | |
}) |
2.Async、Await和Promise
1.定义:
async
是异步的简写,而await
可以认为是async wait
的简写,所以应该很好理解:async
用于申明一个异步的fuction
,而await
用于等待一个异步方法执行完成。
2.简单示例
1.async
方法通常应该返回一个Promise
对象
async function test(){ | |
// 通常异步方法中返回一个Promise对象,如果给定的是字符串,内部也会将其转换为Promise对象 | |
return "hello nodejs"; | |
} | |
console.log(test()) | |
// Promise {[[PromiseState]]: 'fulfilled', [[PromiseResult]]: 'hello nodejs', Symbol(async_id_symbol): 5, Symbol(trigger_async_id_symbol): 1} | |
async function test(){ | |
return new Promise(function(resolve, reject){ | |
resolve("hello nodejs") | |
}) | |
} | |
console.log(test()) |
2.await
方法必须在async
方法中使用
async function test(){ | |
return new Promise(function(resolve, reject){ | |
resolve("hello nodejs") | |
}) | |
} | |
// console.log(await test()) 错误写法 | |
async function main(){ | |
let result = await test(); // await必须用在async方法中 | |
console.log(result) | |
} | |
main(); |