javascript - How do use Javascript Async-Await as an alternative to polling for a statechange?
问题描述
I'd like to accomplish the following using promises: only execute further once the state of something is ready. I.e. like polling for an external state-change.
I've tried using promises and async-await but am not getting the desired outcome. What am I doing wrong here, and how do I fix it?
The MDN docs have something similar but their settimeout is called within the promise--that's not exactly what I'm looking for though.
I expect the console.log to show "This function is now good to go!" after 5 seconds, but instead execution seems to stop after calling await promiseForState();
var state = false;
function stateReady (){
state = true;
}
function promiseForState(){
var msg = "good to go!";
var promise = new Promise(function (resolve,reject){
if (state){
resolve(msg);
}
});
return promise;
}
async function waiting (intro){
var result = await promiseForState();
console.log(intro + result)
}
setTimeout(stateReady,5000);
waiting("This function is now ");
解决方案
你做错的是承诺构造函数执行器函数在创建承诺时立即执行,然后再也不执行。那时state
是false
,所以什么也没有发生。
Promise(和async
/ await
)不能替代轮询。您仍然需要在某个地方进行投票。
好消息:async
函数可以很容易地使用循环和承诺来编写条件代码。
但是不要将代码放在 Promise 构造函数执行器函数中,因为它们的错误处理特性很差。它们旨在包装遗留代码。
相反,试试这个:
var state = false;
function stateReady() {
state = true;
}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function promiseForState() {
while (!state) {
await wait(1000);
}
return "good to go!";
}
async function waiting(intro) {
var result = await promiseForState();
console.log(intro + result)
}
setTimeout(stateReady,5000);
waiting("This function is now ");
推荐阅读
- javascript - Gatsby 中库的条件导入
- java - JAVA List GroupBy 多个字段和 Sum
- javascript - Angular Routing 总是在组件之前显示 url
- makefile - 无法将 grep 的输出存储在 Makefile 中
- android - Flutter - 如何在 AndroidManifest.xml 文件中动态更改谷歌地图 API 密钥
- .net - 用于 PostgreSQL 的 .NET Framework 数据提供程序中出现意外错误
- javascript - 自动将数据从 Firebase 同步到 Google 表格
- javascript - 在猫鼬的自定义验证器中获取参数
- go - Gorilla Mux 相同端点多个查询参数
- java - Kotlin gzip 解压失败