首页 > 解决方案 > 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 ");

标签: javascriptpromiseasync-await

解决方案


你做错的是承诺构造函数执行器函数在创建承诺时立即执行,然后再也不执行。那时statefalse,所以什么也没有发生。

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 ");


推荐阅读