【问题标题】:javascript async fetch functionjavascript异步获取函数
【发布时间】:2020-08-06 14:36:31
【问题描述】:

我正在尝试创建一个递归函数,它为给定数组的每个整数发送一个 PUT 请求,并在其末尾调用另一个函数。

function fetchArchive(arr,state,mailbox){
  if(arr.length == 0){
    load_mailbox(mailbox)
  }
  for(i of arr){
    fetch(`/emails/${arr.shift()}`, {
      method: 'PUT',
      body: JSON.stringify({
          archived: state
      })
    })
    .then(fetchArchive(arr,state,mailbox))
  }
}

但它似乎在获取数组的最后一项之前调用了load_mailbox() 函数。
我知道这应该使用async / await 更好地实现。有人可以举个例子来帮助我理解吗?

更新: 事实证明,下面的代码正在运行

async function fetchArchive(a,s,callback){
  for(i of a){
    await fetch(`/emails/${i}`, {
      method: 'PUT',
      body: JSON.stringify({
          archived: s
      })
    })
    // if i is the last item, load mailbox
    .then(() => { if(i==a[a.length-1] && callback) callback()});
  }
}

【问题讨论】:

    标签: javascript async-await fetch


    【解决方案1】:

    这是 async for..of 循环的正确代码

    async function fetchArchive(arr,state,mailbox){
        console.log(1)
      if(arr.length === 0){
        load_mailbox(mailbox)
      }
        
      for await (const elem of arr){
        await fetch2(elem);
            arr.shift();
    
            console.log({ elem })
    
        fetchArchive(arr,state,mailbox)
      }
    }
    

    但是,此代码不起作用并导致无限递归 :) 我认为在迭代中改变数组是个坏主意。 另外,请记住,then 会收到回调。 所以,then 的正确参数是:

    .then(response=>fetchArchive(respone))
    

    在您的情况下,您不能将 fetchArchive 作为参数传递给 then 方法,因为 fetchArchive 不返回函数

    [更新]

    这是数组索引比较的工作代码:

    const fetchArchive = async (a, s, callback) => {
      for (const [index, value] of a.entries()) {
        await fetch(index)
          // if i is the last item, load mailbox
          .then(() => {
            if (index == a.length - 1 && callback) {
              callback();
            }
          });
      }
    };
    

    关于entries的文档可以找到here

    【讨论】:

    • 感谢您的回答。我尝试使用我刚刚在问题末尾添加的异步功能。你怎么看?
    • 现在好多了,但是这里还有一个问题:i==a[a.length-1]。你正在尝试将价值与价值进行比较。知道它是否是数组结尾的最好方法是比较数组索引。当值可以是任何东西时,索引总是整数。请在我的回答中查看更新
    • 现在看起来好多了,谢谢!!
    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2018-09-19
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多