警告⚠:await has no effect on the type of this expression.
警告翻译后的意思是:在当前表达式前面添加await没意义。
在现代 JavaScript 开发中,
async
和await
关键字提供了处理异步操作的简洁方式。尽管它们的使用非常普遍,但在某些情况下,开发过程中可能会遇到“await has no effect on the type of this expression”的错误提示。
1.什么是 await
?
await
是一个操作符,用于等待一个Promise 对象。它只能在async
函数内部使用。使用await
可以让异步代码的写法看起来更像同步代码,从而提高可读性。
async function getData() {
const response = await axios.get('https://api.example.com/data');
const data = await response.json();
return data;
}
2.什么是“await has no effect on the type of this expression”?
在一个不返回 Promise 的表达式上使用
await
时, 编译器会抛出“await has no effect on the type of this expression”警告。这意味着await
在这个上下文中没有实际的效果,因为它所等待的不是一个 Promise。
/**
* await 被用在一个数字上。由于 5 不是一个 Promise,提示 await 在这里没有效果
*/
async function example() {
// 一般这仅仅是一个警告,因为await后边也可以跟着其他表达式,比如一个常量表达式
const result = await 5;
console.log(result);
}
3.解决方案
需要确保
await
后面跟的是一个 Promise。以下是一些常见的解决方案:
33.1 确保使用 Promise
async function example() {
const promise = new Promise((resolve) => setTimeout(() => resolve(5), 1000));
const result = await promise; // 这里是有效的
console.log(result); // 输出 5
}
3.2 检查函数返回值
在调用一个函数并使用
await
,确保该函数返回的是一个 Promise。
function getNumber() {
return Promise.resolve(5);
}
async function example() {
const result = await getNumber(); // 这里是有效的
console.log(result); // 输出 5
}
“await has no effect on the type of this expression” 警告通常是由于在不返回 Promise 的表达式上使用
await
导致的。通过确保await
后面跟的是一个 Promise,若不需要等待某个表达式,可以移除await
,有效地避免这一警告。