async/await的一些记录

1. await必须在async函数里面引用

2. async函数必定返回一个promise对象,但返回的内容可以是任意,如下面的测试,返回了内容为布尔值的promise对象

3. 正常情况下,await后面跟着一个返回promise对象的函数

4. 接收await xxx;的变量(或常量)是promise对象xxx返回的内容

 

 测试代码:

async function testFun(i) {
    if (i > 0) return true;
    else return false;
}

async function testFun2() {
    console.log(typeof(testFun(1))); // 打印testFun(1)的返回类型,结果为object,说明返回的是一个promise对象
    const fn = testFun(1); 
    console.log('fn is ', typeof(fn)); // 打印fn的类型,结果为object,与上一级打印无异
}

async function testFun3() {
    console.log(typeof(testFun(1))); // 打印testFun(1)的返回类型,结果为object,说明返回的是一个promise对象
    const fn = await testFun(1); 
    console.log('fn is ', typeof(fn)); // 打印fn的类型,结果为boolean,说明经过在函数前面加上await,fn最终接收到的是一个boolean类型的数据
    console.log('fn ', fn); // 打印fn的值,结果为true
}

console.log('testfun2打印结果:')
testFun2();

console.log('testFun3打印结果:')

testFun3();

 打印结果:

testfun2打印结果:
object
fn is  object
testFun3打印结果:
object
fn is  boolean
fn  true

 

 

 

posted @ 2020-04-10 17:22  JonnyOu1012  阅读(25)  评论(0编辑  收藏  举报