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

问题描述 投票:0回答:1

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

这是我的意思的一个例子:

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

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

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

我怎样才能确保我成功地批量处理所有事情?每个create都是一个承诺,但我无法使用Promise.all作为包装器,因为我收到以下错误:Cannot read property 'Symbol(Symbol.iterator)' of undefined

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

javascript
1个回答
1
投票

你的代码应该是:fetch(url, config(item)).then(handleRes).catch(handleErr)调用你的方法的代码应该使用Promise.allitems.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解释承诺。

© www.soinside.com 2019 - 2024. All rights reserved.