await 调用的函数不一定必须是 async 函数。

 

await 关键字通常用于 async 函数内部,用来等待一个 Promise 对象的解决。但如果被 await 调用的对象不是 Promise ,那么它会被直接返回。

 

怎么理解呢?下面我通过例子和动态图来跟大家一起学习记录一下。

 

 

function notPromiseFunction() {
  return 42;
}

async function example() {
  const result = await notPromiseFunction(); 
  console.log(result); 
}
example();

 

然而,如果希望通过 await 实现异步等待的效果,通常被 await 调用的应该是返回 Promiseasync 函数。比如:

 

async function promiseFunction() {
  return new Promise((resolve) => {
    setTimeout(() => resolve(100), 1000);
  });
}

async function anotherExample() {
  const result = await promiseFunction();
  console.log(result);
}
anotherExample();

在这个例子中,通过 await 等待了 promiseFunction 中异步操作的完成,并获取到最终的结果。

 

await 调用的函数不一定必须是 async 函数。  await 关键字通常用于 async 函数内部,用来等待一个 Promise 对象的解决_动态图

 

 如果没有写return的情况 那么执行结果是什么样子的呢?

<script>
export default {
	name: 'test',
	data() {
		return {
			msg: '李荣浩'
		}
	},
	async mounted() {
		const test = () => {
			new Promise(resolve => {
				setTimeout(() => {
					this.msg = '大拿哥'
					resolve()
				}, 1000)
			})
		}

		await test()
		this.msg = '等待你的人'
	}
}
</script>
<template>
	<h2>{{ msg }}</h2>
</template>

 

await 调用的函数不一定必须是 async 函数。  await 关键字通常用于 async 函数内部,用来等待一个 Promise 对象的解决_异步操作_02

 

 

那么我们改造一下代码

await 调用的函数不一定必须是 async 函数。  await 关键字通常用于 async 函数内部,用来等待一个 Promise 对象的解决_异步操作_03

<script>
export default {
	name: 'test',
	data() {
		return {
			msg: '李荣浩'
		}
	},
	async mounted() {
		const test = () => {
			return new Promise(resolve => {
				setTimeout(() => {
					this.msg = '大拿哥'
					resolve()
				}, 1000)
			})
		}

		await test()
		this.msg = '等待你的人'
	}
}
</script>
<template>
	<h2>{{ msg }}</h2>
</template>

 

 

await 调用的函数不一定必须是 async 函数。  await 关键字通常用于 async 函数内部,用来等待一个 Promise 对象的解决_动态图_04