【问题标题】:How to make Async Await Function in React Native?如何在 React Native 中制作异步等待功能?
【发布时间】:2019-08-29 01:29:29
【问题描述】:

我想创建一个关于使用react-native-fetch-blob 将照片上传到 Firebase 存储的功能。我正在使用 Redux,您可以在下面找到操作函数:

我的问题是 uploadImage 函数没有像异步一样运行。 Firebase 函数在 uploadImage 之前运行,所以应用程序给我一个错误。

我想我不能做一个异步函数。我该如何解决?

uploadImage() 函数:

const uploadImage = async (imageSource, whereToUpload) => {
  let imageURL = '';
  const mime = 'image/jpg';
  const { Blob } = RNFetchBlob.polyfill;
  const { fs } = RNFetchBlob;

  window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
  window.Blob = Blob;

  console.log('URI =>', imageSource.uri);

  let imgUri = imageSource.uri;
  let uploadBlob = null;
  const imageRef = firebase.storage().ref(whereToUpload + '/' + imageSource.fileName);
  const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
  await fs.readFile(uploadUri, 'base64')
  .then((data) => Blob.build(data, { type: `${mime};BASE64` }))
  .then((blob) => {
    uploadBlob = blob;
    return imageRef.put(blob, { contentType: mime });
  })
  .then(() => {
    uploadBlob.close();
    // eslint-disable-next-line no-return-assign
    return imageURL = imageRef.getDownloadURL();
  })
  .catch((error) => {
    console.log(error);
  });
  return imageURL;
};

主要作用是:

export const addProjectGroup = (
  myUser,
  groupName,
  groupDescription,
  groupProfilePic,
) => dispatch => {
  const groupProfileFinalPic = async () => {
    let finalGroupPicture = { landscape: '' };

    if (_.isEmpty(groupProfilePic.src)) {
      await uploadImage(groupProfilePic, 'groupPictures').then((imageURL) => {
      console.log('İŞLEM TAMAM!');
      console.log('SELECTED IMAGE URL =>', imageURL);
      finalGroupPicture.landscape = imageURL;
    });
    } else {
      finalGroupPicture.landscape = groupProfilePic.src.landscape;
    }
    return finalGroupPicture;
};

console.log("final group profile pic =>", groupProfileFinalPic());

  // Önce grubu yaratalım..
  // eslint-disable-next-line prefer-destructuring
  const key = firebase
    .database()
    .ref()
    .child('groups')
    .push().key;

  firebase
    .database()
    .ref('/groups/' + key)
    .set({
      admin: {
        email: myUser.email,
        name: myUser.name,
        uid: myUser.uid,
      },
      groupName,
      groupDescription,
      groupProfilePic: groupProfileFinalPic(),
      projects: '',
    })
    .then(() => {
      console.log('Groups oluşturuldu.');
    })
    .catch(e => {
      Alert.alert('Hata', 'Beklenmedik bir hata meydana geldi.');
      console.log(e.message);
    });

  dispatch({
    type: ADD_PROJECT_GROUP,
  });
};

【问题讨论】:

    标签: reactjs react-native async-await


    【解决方案1】:

    你不是在等待groupProfileFinalPic()。这应该在创建您要调度的操作之前完成。

    groupProfileFinalPic().then(groupProfilePic => {
        return firebase
            .database()
            .ref("/groups/" + key)
            .set({
                admin: {
                    email: myUser.email,
                    name: myUser.name,
                    uid: myUser.uid
                },
                groupName,
                groupDescription,
                groupProfilePic,
                projects: ""
            })
            .then(() => {
                console.log("Groups oluşturuldu.");
            })
            .catch(e => {
                Alert.alert("Hata", "Beklenmedik bir hata meydana geldi.");
                console.log(e.message);
            });
    });
    

    我不知道最后一次调度的目的是什么,您可能想在其中一个回调中执行此操作。您的代码是针对 SO 问题的详细说明,但我希望这无论如何都会有所帮助。

    【讨论】:

    • 你能解释一下修复代码吗?非常感谢。
    【解决方案2】:

    您在同一通话中同时使用awaitthen。要使用await,您可以像这样安排它

    const uploadImage = async (imageSource, whereToUpload) => {
        ...
        try {
            let data = await RNFS.fs.readFile(uploadUri, 'base64')
            let uploadBlob = await Blob.build(data, { type: `${mime};BASE64` }))
            ...etc...
            return finalResult
        catch (e) {
            // handle error
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2021-04-13
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多