react-native warning:可能未处理的承诺:无法找到变量:listeners

时间:2016-12-19 15:01:40

标签: reactjs react-native promise warnings

当我运行react-native移动应用程序时,我收到此警告。 我尝试将带有react-native-image-picker的照片上传到firebase(在存储中),并将此照片的URL保存在firebase(数据库)中。上传成功,但当程序尝试将URL保存在数据库中时,应用程序会发出警告:"可能未处理的承诺拒绝:无法找到变量:侦听器"。 以下是我的代码:

ImagePicker.showImagePicker(options, (response) => {

  let filePath = response.path;
  let fileName = this.props.imageName;
  let rnfbURI = RNFetchBlob.wrap(filePath);
  Blob
     .build(rnfbURI, { type : 'image/png;'})
     .then((blob) => {
  // upload image using Firebase SDK
        this.props.bdd.storage()
            .ref('images')
            .child(fileName)
            .put(blob, { contentType : 'image/jpg' })
            .then((snapshot) => {

                 console.log('Uploaded', snapshot.totalBytes, 'bytes.');
                 console.log(snapshot.metadata);
                 console.log('downlo='+snapshot.metadata.downloadURLs[0]);
                var ref = this.props.bdd.database().ref('promotions/'+ fileName);
                alert(snapshot.metadata.downloadURLs[0]);
                ref.update({
                  image_url:snapshot.metadata.downloadURLs[0]
                });
               }).catch(function(error) {
                console.error('Upload failed:', error);
                 });
     })   

});

}

2 个答案:

答案 0 :(得分:1)

你确实没有处理外部承诺(Blob.build一)拒绝。问题是,如果此操作失败,抛出等等,那么您将无法恢复,因为您根本不处理此情况。

正确的方法是使用return this.props.bdd.storage()返回内部承诺,并将catch块添加到外部块。像这样:

Blob
  .build(rnfbURI, {
    type: 'image/png;'
  })
  .then((blob) => {
    // upload image using Firebase SDK
    return this.props.bdd.storage()
      .ref('images')
      .child(fileName)
      .put(blob, {
        contentType: 'image/jpg'
      })
      .then((snapshot) => {

        console.log('Uploaded', snapshot.totalBytes, 'bytes.');
        console.log(snapshot.metadata);
        console.log('downlo=' + snapshot.metadata.downloadURLs[0]);
        var ref = this.props.bdd.database().ref('promotions/' + fileName);
        alert(snapshot.metadata.downloadURLs[0]);
        ref.update({
          image_url: snapshot.metadata.downloadURLs[0]
        });
      })
      .catch(function(error) {
        console.error('Upload failed:', error);
        throw error;
      });
  })
  .catch(error => {
    console.log('One of the above operations failed', error)
  })

请注意这一部分:

.catch(function(error) {
  console.error('Upload failed:', error);
  throw error;
})

如果this.props.bdd.storage()失败,您将进入此错误处理程序,然后通过重新throw错误使其进一步传播到外部catch块。所以可以处理所有可能的拒绝。

答案 1 :(得分:0)

我认为这是因为你没有做出完整的承诺,通常它看起来像这样:

yourPromise()
.then((response) => {/*this callback will be executed if promise is completed*/}, 
      (cause) => {/*this callback will be executed if promise is rejected*/})
.catch((err) => {/*this callback will be execute if some exception is thown*/});