尝试部署后端firbase函数时,promise中的错误

时间:2019-05-20 20:22:23

标签: javascript firebase promise

我第一次使用firebase作为我的服务器和数据库,并尝试将firebase后端功能部署到firebase,我在控制台中不断收到有关不嵌套我的诺言的错误“错误每个then()应该返回一个值或承诺/总是回报   52:16警告避免嵌套承诺诺言/不嵌套   52:16警告“避免嵌套promise promise / no-nesting”,以其他方式编写此promise?

let Promise = require('promise');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();




exports.addSimilarImages = 
functions.firestore.document('photos/{document}')


 .onCreate((snap, context) => {

       console.log('SNAP', snap)
       console.log('CONTEXT', context) 


by recreating a google storage style url called photoUrl
       const data = snap.data();
       console.log('DATA IN IS', data)
       const photoUrl = "gs://" + data.bucket + "/" + 
data.fullPath;
       conolse.log('url is', photoUrl);
 return Promise.resolve()
        .then(() => {
                //we put the photoUrl through the vison API and it 
returns a list of similar images 
               return visionClient.webDetection(photoUrl);

        })  //place these similar images in a array 
         .then(results => {
               console.log('VISION data all is: ', results)
               const webDetection = results[0].webDetection 

                 //update the document in the photos collection 
with the similarImages images 
               let similarImages = [];
               if (webDetection.visuallySimilarImages.length) {

webDetection.visuallySimilarImages.forEach(image => {
                               similarImages.push(image);
                       });
               }

                console.log('similarImages', similarImages)



db.collection('photos').doc(context.params.document).update({ 
similarImages })


         })
              .catch(err => console.log(err));
 }) 
   .then(res => console.log('pictures added'))
   .catch(err => console.log(err)); 

1 个答案:

答案 0 :(得分:0)

一开始你做得很好:


class EditorsEditorGroupsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('editors_groups');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Editors', [
            'foreignKey' => 'user_id',
            'className' => 'Users'
        ]);
        $this->belongsTo('EditorGroups', [
            'foreignKey' => 'group_id',
            'className' => 'Groups'
        ]);
    }
}

但是最后,在您的诺言中,您只是做

    return visionClient.webDetection(photoUrl); //Returns a promise
})  //place these similar images in a array 
  .then( /* ... */ //Work on the promise

什么时候可以做

db.collection('photos').doc(context.params.document).update({ 
similarImages })
               .then(res => console.log('pictures added')) //Promise in promise
               .catch(err => console.log(err));//Promise in promise

         }) //End of promise