How to avoid “Excessive number of pending callbacks: 501” error during images download in React Native?

我与影子孤独终老i 提交于 2020-12-13 04:35:05

问题


I need to download a collection of images on button press. Currently, I'm doing it this way using react-native-fs:

const downloadImageItem = async (imgUrl, id) => {
  const path = `${RNFS.DocumentDirectoryPath}/${id}.jpg`;

  RNFS.downloadFile({
    fromUrl: imgUrl,
    toFile: path,
  });
};
const downloadImages = async (items) => {
  for (const item of items) {
    if (item.images.length) {
      await downloadImageItem(item.images[0].thumb, item.images[0].id);
    }
  }
  return Promise.resolve();
};

Calling the function from my reducer for 3 types of items:

await downloadImages(items_one);
await downloadImages(items_two);
await downloadImages(items_three);

My issue is that sometimes I receive an error message that says: Excessive number of pending callbacks: 501

Is there a better way of doing the same thing, so that the error does not appear?


回答1:


A similar issue was opened on the react-native repository in December 2019, it still hasn't been closed or addressed but I think you may find this comment useful.

The problem being described there is that queueing too many Promise calls can be problematic. The commenter suggested using a Promise utility function called Promise.map() which has concurrency control out of the box, from the bluebird library.




回答2:


Instead of using await inside for, try using for await

for await (variable of iterable) {
  sentence
}
const downloadImages = async (items) => {
  for await(const item of items) {
    if (item.images.length) {
      downloadImageItem(item.images[0].thumb, item.images[0].id);
    }
  }
  return Promise.resolve();
};


来源:https://stackoverflow.com/questions/61480089/how-to-avoid-excessive-number-of-pending-callbacks-501-error-during-images-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!