多功能事件/回调?

时间:2018-07-28 09:20:45

标签: javascript node.js reactjs

我正在尝试创建一个函数,该函数从Firebase上传函数传回事件,然后在UI中显示进度

我有一个函数,可以像这样处理图像的上传:

import firebase from '~/firebase';
import hashSum from 'hash-sum';
import events from 'events'

async function uploadFile(image, design) {
  const eventEmitter = new events.EventEmitter();
    const hashId = hashSum(image.name + Date.now())
    const meta = {
      customMetadata: {
        namne: image.name
      }
    }
    const storageRef = firebase.storage().ref().child(`designs/${firebase.auth().currentUser.uid}/${design.id}/${hashId}.png`);
    const task = storageRef.put(image, meta);
    task.on('state_changed',
      (snapshot) => {
        const percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100;
        eventEmitter.emit('progress', percentage)
        console.log(percentage)
      },
      (err) => {
        eventEmitter.emit('error', err)
      },
      () => {
        task.snapshot.ref.getDownloadURL().then(url => {
          eventEmitter.emit('done', {url, hashId})
        })
      }
    )
}



export { uploadFile }

然后在我的UI中,我想接收这些事件并对其进行处理:

const upload = await uploadFile(selectedFile, {id: this.props.match.params.id})
upload.on('done', async (data) => {
  files.push({id: data.hashId ,name: selectedFile.name, url: data.url})
  await firebase.firestore().collection('designs').doc(firebase.auth().currentUser.uid).collection('designs').doc(this.props.match.params.id).update({
    files
  })
})
upload.on('error', (err) => {
  message.error(err)
})
upload.on('progress', (percent) => {
  this.setState({
    uploadProgress: percent
  })
})

现在显然我在做错事,因为upload.on不是一个函数。谁能建议如何处理这个问题,或者是否有更简单的方法来返回已经存在的事件?

0 个答案:

没有答案