You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
async function test(){
var res = await Math.random() * 10
if(res>5)return true
else return false
}
test().then(val=>console.log(val))
// 模拟
function mockTest(){
return Promise.resolve(Math.random()*10).then(function(res){
if(res>5)return true
else return false
})
}
mockTest().then(val=>console.log(val))
使用Async包裹一个function,返回 promise
async function foo(arg){
if(arg) return true
else return new Error('error!')
}
foo(false)
.then(val=>console.log(val))
.catch(val=>console.log(val))
如果不存在继发关系,则让他们同时触发
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
多层调用函数同步执行
每层都要加 await
async function f(timer) {
await new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log(`${timer}之后`)
resolve()
},timer)
})
}
async function foo () {
try {
await f(1000)
console.log('done')
}catch(e){
console.log(e)
}
}
foo()
The text was updated successfully, but these errors were encountered:
介绍
Generator 函数的语法糖。
Async 表示函数内有异步操作、Await 表示需要等待后面的表达式的执行结果。
特性
async 函数返回一个 Promise 对象
async函数内部返回值作为then回调函数的参数。
如果async函数内部抛出异常,则返回的promise变成reject状态,被catch回调函数接收到。
async 函数返回的对象,必须要等到内部的所有 await 命令的 Promise 对象执行完,状态才会发生改变
正常情况下,await 命令后面跟的是thenable对象,如果不是也会立即被转换成 resolve 的 Promise
await 实际上接收到是后面 promise 调用 then方法的 resolve 回调函数参数。
用 Promise.resolve 来模拟 async/await
使用Async包裹一个function,返回 promise
如果不存在继发关系,则让他们同时触发
多层调用函数同步执行
每层都要加 await
The text was updated successfully, but these errors were encountered: