javascript - 使用批量更新项目 - 如何正确处理错误和成功?

标签 javascript

我试图一次更新多个项目,并且我必须为每个项目发出网络请求。我正在使用 fetch 来发出请求。

以下是我的意思的示例:

const updateItems = items => items.forEach(item => api.create(item))

api.create 可能看起来像这样:

create: item => fetch(url, config(item)).then(handleErr).then(handleRes)

如何确保我成功批处理所有内容?每个 create 都是一个 promise ,但我在使用 Promise.all 作为包装器时遇到了麻烦,因为我收到以下错误: Cannot read property 'Symbol(Symbol.iterator)' of undefined

但是,更新成功了,所以我做错了什么!

最佳答案

你的代码应该是: fetch(url, config(item)).then(handleRes).catch(handleErr) 并且调用你的方法的代码应该使用 Promise.all code> 和 items.map ,以便调用代码可以对结果执行某些操作(失败和成功)。

一个例子(这里updateItems不会捕获任何错误,调用代码会捕获):

const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
  items.map(//map array of items to array of promises that don't reject
    item =>
      updateItems(item)
      .then(
        undefined,//do not handle resolve yet
        //when you handle the reject this ".then" will return
        //  a promise that RESOLVES to the value returned below (new Fail([item,err]))
        err=>new Fail([item,err])
      )
  )
)
.then(
  responses => {
    console.log("failed requests:");
    console.log(
      responses.filter(//only Fail type
        isFail
      )
    );
    console.log("resolved requests:");
    console.log(
      responses.filter(//anything not Fail type
        response=>!isFail(response)
      )
    );
  }
);

该代码来自 following answer解释 promise 。

关于javascript - 使用批量更新项目 - 如何正确处理错误和成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917895/

相关文章:

javascript - 查看复制和粘贴格式

javascript - 从 Redux 状态属性渲染 React 组件

javascript - react 表过滤和响应

javascript - 从给定字符串中检索子字符串

javascript/jquery 更改 location.href

javascript - jquery.js?v=1.9.1 :4421 Uncaught Error: Syntax error, 无法识别的表达式:[对象对象]

javascript - 如何在javascript中手动抛出语法错误

javascript - 可能会破坏我 Javascript 职业生涯的基本 boolean 逻辑

javascript - 使用 toastr.js 时 toastr 未定义

javascript - 从单独的 gulp 文件导入/读取变量