参考  https://segmentfault.com/a/1190000007535316

案例1:

async function testAsync() {
    return "hello async";
}

const result = testAsync();
console.log(result);

结果是:

Promise { 'hello async' }

返回的是一个 promise 对象

案例2:

function getSomething() {
    return "something";
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();

结果是:

something hello async

await  不仅用于等待promise对象,还可以用于任何其他值,是一样的

案例3:

 
function getSomething() {
    setTimeout(() => {
        return "something";
    }, 3000)
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();

结果是:

undefined 'hello async'

对于setTimeout也是一样,没有特殊待遇,会直接输出结果,如果在setTimeout前面增加return,则会将setTimeout函数返回

 

Timeout {
  _called: false,
  _idleTimeout: 1,
  _idlePrev: [TimersList],
  _idleNext: [Timeout],
  _idleStart: 85,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: false,
  [Symbol(unrefed)]: false,
  [Symbol(asyncId)]: 8,
  [Symbol(triggerId)]: 1 }  'hello async'

案例4:

function getSomething() {
    return new Promise(() => {
        setTimeout(() => {
            return "something";
        }, 3000)
    })
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();

结果是:

没有输出值

案例5:

function getSomething() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("something");
        }, 3000)
    })
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();

结果是:

3s之后输出  something hello async

案例6:

function getSomething() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("something");
            return 111111;
        }, 3000)
    })
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();

结果是: 

3s之后输出  something hello async