javascript - 像使用 setTimeout 的承诺一样使用 setTimeout 构建异步不起作用
问题描述
在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function他们说写作
async function foo() {
return 1
}
和写一样
function foo() {
return Promise.resolve(1)
}
所以这意味着如果我们想把一个 Promise '转换'成一个异步函数,我们必须resolve(promise_result)
用return promise_result
.
但是当我尝试使用setTimeout
它async
时不起作用:
const test1 = async () => {
setTimeout(
() => {
return 5;
},
2000,
)
}
const test2 = () => new Promise(
(resolve, reject) => {
setTimeout(
() => resolve(25),
1000
)
}
)
const execute = async () => {
const result = await test1();
console.log(result); // undefined
}
execute();
如果我使用await
它test2
可以工作,但它不能工作test1
。这是为什么 ?async/await
仅用于处理未使用的承诺,.then
或者我可以使用async
with而不是return result
使用Promise
with resolve
?
解决方案
它未定义,因为test1
不返回任何东西。仔细看看你在匿名函数中返回它
const test1 = async () => { // <--- this function returns nothing back. Nothing means "undefined"
setTimeout(
() => { // <---- you return it here back in your anonymous function witch makes no sense
return 5;
},
2000,
)
}
推荐阅读
- java - Spring Outbound SFTP 集成流式传输
- php - 在 wordpress 插件中添加引导程序时遇到问题
- docker - 无法通过 nodeport 访问 Kubernetes 服务
- csv - 使用 sql 和 csv 文件进行 Jmeter 功能测试验证
- java - 如何在 TornadoFx 中为 BarChart 条着色?
- python - Python:区分大小写的计数器
- python - 为熊猫中的列添加具有重复值的数字
- ios - 多个容器视图 VS 链接到单个容器视图的多个视图控制器
- listview - 使用 react native listView 时 iOS 中的内存泄漏
- php - Laravel 5.7 中的 php 多维数组循环问题