【问题标题】:javascript es6 promise to call async actions in while loopjavascript es6 承诺在 while 循环中调用异步操作
【发布时间】:2016-03-01 11:55:45
【问题描述】:

我有一个类似的功能:

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 调用中获得了所需的状态。

直到我从我想要每 5 秒检查一次的 api 调用中获得所需的状态..

但这不起作用.. 我已经用谷歌搜索了,但没有根据我的需要理解解决方案。 如果有人能回答这个问题将非常有帮助。

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

谢谢

【问题讨论】:

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

把这个助手放在你所有的脚本中:

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

然后永远不要再调用setTimeout(它具有糟糕的错误处理特性)。

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

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

【讨论】:

  • 或者只是.then(myFunction)
【解决方案2】:

当前代码有一些拼写错误(thenmyFunction 上缺少右括号)和一个很大的缺陷。

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

现在,您的代码流程执行此操作..

  1. 虽然 ...
  2. 创建一个函数,但现在不要运行它...
  3. 回到当下……

在前 5 秒过去之前,第 2 行将运行数千次..

这是您的代码,没有错别字,但主要问题仍然存在。

function myFunction()
{
    var status = null;
    while (status != "complete")
    {
        setTimeout(function()
        {
            callApi('myurl').then(response => { status = response.status }); //<-- missing ')'
        }, 5000);
    }
}

至于主要问题,您不应该编写每 X 秒检查一次的代码,如果发生了什么,您应该使用 Promise API 并向done 事件添加一个函数。 这样你想要的代码只有在异步函数中的前一个代码完成时才会运行。

【讨论】:

  • 你能举个例子用Promise Api
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 2017-10-30
  • 2018-05-04
相关资源
最近更新 更多