async与await的原理解析
async原理
async的意思就是用来声明这个function是一个异步操作。async 函数返回的是一个Promise对象,如果 async 函数没有返回值,它会返回Promise.resolve(undefined)。在没有 await 的情况下执行 async 函数,会立即执行,不会阻塞后面的语句。
await原理
await命令只能用在async函数中,可以说 await 在等 async 函数,它等的实际是一个返回值。注意到 await 不仅用于等 Promise 对象,它可以等任意表达式的结果。
异步与同步操作如何使用
//用代码去理解一下异步与同步的使用(async)
async function timeout() {
return 'hello world'
}
console.log(timeout());
console.log('cxq');
//Promise {<resolved>: "hello world"}
//cxq
解释:用async返回的对象是一个promise对象,所以要用promise里面的then()方法来接收一下
async function timeout(){
return 'hello word'
}
timeout().then(result=>{
console.log(result)
})
console.log( '我在后面,但先执行');
//我在后面,但先执行
//hello word
//获取到hello word的同时也没有阻止下边代码的执行
//这个就是异步操作,在操作其他函数时不会影响下面函数的操作
//await的使用
async function timeout(){
return 'hello word'
}
timeout().then(result=>{
console.log(result)
})
console.log(await 'cxq');
//hello word
//cxq
加了一个await之后就变成同步操作了。其实就是按循序执行,同步执行。