【问题标题】:ES6 looping with async call带有异步调用的 ES6 循环
【发布时间】:2019-02-15 01:28:15
【问题描述】:

我需要编写一些 Javascript(ES6 版本)来执行以下任务:

  1. 字符串为“item1,item2,item3,item4,item5”,
  2. fetch() 使用此字符串的 URL。
  3. 如果响应标志成功,则完成并退出。
  4. 如果响应标志为失败,则删除最后一项 (item5),因此现在字符串为“item1,item2,item3,item4”并重复第 2 步。
  5. 如果没有更多物品可掉落,请退出。

项目的总数是可变的。因此,我计划使用 do-loop 执行此任务,使用以下结构:

//suppose str = 'item1,item2,item3,....itemN'
do {
    fetch(url, {param1: str}).then(response => {
        //check the response flag, if success, done and exit.
        //if not success, drop one item and re-do fetch
    })
}

问题是 fetch 是一个异步调用,所以我不能强制每个 fetch 按顺序执行。

我需要确保仅在前一个 fetch() 失败时才执行新的 fetch()。有什么想法吗?

【问题讨论】:

  • function doFetch() { if (arr.length>0) fetch(url, {param1: arr.pop()}).then(response => { if (!success) doFetch(); })
  • 你会用 ES8 吗?

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

你可以使用递归:

function fetchRecursive(param) {

  return fetch(url, {param1: param})
    .then(response => response.ok ? response : Promise.reject(new Error(response.status)))
    .catch((err) => {
      if (param.length > 1) {
        return fetchRecursive(param.slice(0,-1));
      } else {
        return Promise.reject(err);
      }
    })
}

fetchRecursive([ 'item1', 'item2', 'item3', 'item4' ])
  .then(response => { ... })
  .catch(err => { ... });

【讨论】:

  • (使用 HTML5 fetch API 而不是一些任意的 fetch 函数,它需要是 fetch(…).then(response => response.ok ? response.json() : Promise.reject(new Error(response.status))).catch(…) 左右,但通用方法 +1)
  • 你是对的。此外,我的代码并不完全正确。修好了。
【解决方案2】:

也许你可以使用递归,像这样:

//str = 'item1,item2,item3,....itemN'
function fetchUrl(str){
  fetch(url, {param1: str}).then(response => {
        if(response.success){
          //exit from the program
          return response;
        }
        else
        {
          return fetchUrl(str.split(",").pop().join(","));
        }
    });
}

【讨论】:

    【解决方案3】:

    在 for 循环中使用 await 而不是 then

    【讨论】:

    • 对它们之间的差异以及为什么重要的更多解释会有所帮助!
    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 2018-03-09
    • 2013-10-20
    • 2018-12-10
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多