ES7正式纳入async/await,用来简化Promise异步操作,在async/awiat出现之前,开发者只能通过链式.then()的方式处理Promise异步操作。
async
async function testAsync() {
return "hello async";
}
let result = testAsync();
console.log(result)
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "hello async"}
从结果中可以看到async函数返回的是一个promise对象,如果在函数中 return 一个直接量,async 会把这个直接量通过 Promise.resolve() 封装成 Promise 对象。
async function testAsync1() {
console.log("hello async");
}
let result1 = testAsync1();
console.log(result1);
// hello async
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: undefined}
结果返回Promise.resolve(undefined)。
await
- 使用await修饰的话,函数必须使用async
- 在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行
- await的必须在异步函数中使用,其中await有限制(不允许出现在箭头函数中;不允许出现在同步函数声明中;不允许出现在同步函数表达式中;如果在同步函数中使用await就会抛出SyntaxError)
示例
function testSometing() {
console.log("执行testSometing");
return "testSometing";
}
async function testAsync() {
console.log("执行testAsync");
return Promise.resolve("hello async");
}
async function test() {
console.log("test start...");
const v1 = await testSometing();//关键点1
console.log(v1);
const v2 = await testAsync();
console.log(v2);
console.log(v1, v2);
}
const promise = new Promise((resolve)=> {
console.log("promise start..");
resolve("promise");
});//关键点2
promise.then((val)=> console.log(val));
console.log("test end...")
// test start...
// 执行testSometing
// promise start..
// test end...
// testSometing
// 执行testAsync
/*promise*/
// hello async
// testSometing hello async
当test函数执行到
const v1 = await testSometing();
的时候,会先执行testSometing这个函数打印出“执行testSometing”的字符串,然后因为await会让出线程就会区执行后面的
const promise = new Promise((resolve)=> {
console.log("promisestart..");
resolve("promise");
});//关键点2
然后打印出“promise start…”接下来会把返回的这promise放入promise队列(Promise的Job Queue),继续执行打印“test end…”,等本轮事件循环执行结束后,又会跳回到async函数中(test函数),等待之前await 后面表达式的返回值,因为testSometing 不是async函数,所以返回的是一个字符串“testSometing”,test函数继续执行,执行到
const v2 = await testAsync();
和之前一样又会跳出test函数,执行后续代码,此时事件循环就到了promise的队列,执行promise.then((val)=> console.log(val));then后面的语句,之后和前面一样又跳回到test函数继续执行。