JavaScript - 使用预定义参数将数据传递给回调

JavaScript - Passing data to callback with predefined parameters

如果有人能帮助我解决这个问题,我将不胜感激。我认为可能有一个简单的解决方案,但我无法解决,这非常令人沮丧。

我正在使用 Expo 开发 React Native 应用程序。他们的 SDK 具有允许用户下载文件的 'downloadResumable' 功能。

回调函数,提供下载进度信息,获取对象'totalBytesWritten', 'totalBytesExpectedToWrite' 道具自动传递给它。

有什么方法可以将我传递给 createDownloadResumable 的 'songId' 参数传递给回调函数,这样回调就不需要引用外部“_id”变量了吗?

提前感谢任何可以帮助我解决这个问题的人!

const { _id } = song;

const callback = ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
  _id,
  totalBytesWritten,
  totalBytesExpectedToWrite
));

const createDownloadResumable = songId => FileSystem.createDownloadResumable(
  link,
  FileSystem.documentDirectory + `${songId}.mp3`,
  {},
  callback,
);

const downloadResumable = createDownloadResumable(_id);

您应该可以通过在这样的闭包中创建回调来做到这一点:

const { _id } = song;

const generateCallback = (songId) => {
  return ({ totalBytesWritten, totalBytesExpectedToWrite }) => dispatch(updateDownloadProgress(
    songId,
    totalBytesWritten,
    totalBytesExpectedToWrite
  ));
}

const createDownloadResumable = (songId) => FileSystem.createDownloadResumable(
  link,
  FileSystem.documentDirectory + `${songId}.mp3`,
  {},
  generateCallback(songId),
);

const downloadResumable = createDownloadResumable(_id);