【问题标题】:React Native Why is my code executing before finishing the task? Promise.all().then() asynchronous issuesReact Native 为什么我的代码在完成任务之前执行? Promise.all().then() 异步问题
【发布时间】:2020-05-05 21:56:43
【问题描述】:

我有这个设置,它通过一个数组运行,并将其保存到手机中,但它会在所有媒体文件下载之前打开 googleUrl。 Promise.all() 不应该处理这个吗?不是应该等mapMediaArray完成,然后.then()剩下的工作吗?

const mapMediaArray = selectedMedia.map(index => {
  let cleanUrl = `${index.mediaUrl.split('?')[0]}`;
  let extension = cleanUrl.split('.').pop();
  RNFetchBlob.config({
    fileCache: true,
    appendExt: extension,
  })
    .fetch('GET', index.mediaUrl)
    .then(res => {
      CameraRoll.saveToCameraRoll(res.path());
    });
});

Promise.all(mapMediaArray).then(() => {
  Linking.openURL(googleUrl);
});

【问题讨论】:

  • 因为你没有 return 来自 map 回调的承诺。尝试记录 mapMediaArray - 这不是一系列承诺
  • @Bergi 刚刚得到一个 undefined 数组。即:[undefined, undefined, undefined] 建议?
  • 我所说的 - 在回调函数中添加缺少的 return 关键字
  • @Bergi 啊!好的,谢谢我在return RNFetchBlob 做的,现在似乎得到了一个承诺!谢谢
  • 顺便说一句,取决于 CameraRoll.saveToCameraRoll(…) 是否是异步的并返回一个承诺,你还需要另一个 return 那里

标签: reactjs react-native asynchronous promise


【解决方案1】:

确实,您在方法中调用了一个 Promise,但您的方法不是一个 Promise。它是一种同步方法,因此只要调用所有同步代码,就会调用 promise.all()。你的方法必须是这样才能被识别为有效的承诺。

const mapMediaArray = selectedMedia.map(index => {
  return new Promise((resolve)=>{
     let cleanUrl = `${index.mediaUrl.split('?')[0]}`;
     let extension = cleanUrl.split('.').pop();
     RNFetchBlob.config({
       fileCache: true,
       appendExt: extension
     })
     .fetch('GET', index.mediaUrl)
     .then(res => {
       CameraRoll.saveToCameraRoll(res.path());
       resolve()
     })
  })
}

和上面的代码一样,你必须返回一个promise然后调用resolve才能让Promise.all正常工作。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
相关资源
最近更新 更多