javascript es6承诺在while循环中调用异步操作

javascript es6承诺在while循环中调用异步操作,javascript,ecmascript-6,es6-promise,Javascript,Ecmascript 6,Es6 Promise,我有一个类似于: function callApi(url){ return fetch(url).then(response => {return response.json()} ).then(response => {return response}) } function myFunction() { var status = null; while (status != "complete") { setTimeout

我有一个类似于:

function callApi(url){
    return fetch(url).then(response => {return response.json()}
       ).then(response => {return response})
}

function myFunction() {
    var status = null;
    while (status != "complete") {
        setTimeout(function(){
            callApi('myurl').then(response => {
               status = response.status
            }
         }, 5000)
    }
在这里,我只想检查我是否从api调用中获得了所需的状态

直到我从api调用中获得所需的状态,我希望每5秒检查一次

但是这不起作用。。 我已经在谷歌上搜索过了,但还不了解我需要的解决方案。 如果有人能回答这个问题,那将非常有帮助

我是javascript新手。我在某个地方看过有关es6的
promise。
如果有人能解释一下,那就太好了


谢谢

当前代码有一些打字错误(在
上缺少右括号,然后是
myFunction
)和一个大缺陷

setTimeout
不是一个阻塞函数,因此您在
中运行,而
循环次数比您想象的要多。
您正在创建许多“稍后函数”,这些函数将在5秒后执行

现在,您的代码流可以做到这一点

  • 创建一个函数,但现在不要运行它
  • 返回到WHILE
  • 即使在前5秒过去之前,第2行仍将运行数千次

    这是您的代码,没有输入错误,但主要问题仍然存在

    function myFunction()
    {
        var status = null;
        while (status != "complete")
        {
            setTimeout(function()
            {
                callApi('myurl').then(response => { status = response.status }); //<-- missing ')'
            }, 5000);
        }
    }
    
    函数myFunction()
    {
    var状态=空;
    while(状态!=“完成”)
    {
    setTimeout(函数()
    {
    
    callApi('myurl')。然后(response=>{status=response.status});//将此帮助程序放入所有脚本中:

    var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    然后再也不要调用
    setTimeout
    (它具有可怕的错误处理特性)

    另外,
    while
    是一个同步构造,在这里不起作用。您可以使用异步“递归”。此外,要对异步操作排序,承诺必须链接:

    function myFunction() {
      return callApi('myurl').then(response =>
        response.status == "complete" ? response : wait(5000).then(() => myFunction()));
    }
    

    看一看,您可以(也应该)完全省略
    。然后(response=>{return response})
    ,该行为不会改变位或只是
    。然后(myFunction)
    您可以使用
    Promise Api
    给出示例吗