Firebase函数返回并且promise不会退出函数 [英] Firebase Functions returns and promises do not exit the function

查看:100
本文介绍了Firebase函数返回并且promise不会退出函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是Firebase世界的初学者,我一直试图弄清楚下面的代码是什么问题,但我在所有方面都失败了。

I am still a beginner in the Firebase world and I have been trying to figure out what the problem is with the below code but I failed in all possible ways.

代码应该从数据库中的用户配置文件中检索 uid ,然后使用它来更新身份验证配置文件,然后再次更新数据库配置文件,如果身份验证配置文件更新成功。

The code is supposed to retrieve the uid from the user profile in the database, then use it to update the authentication profile, then again to update the database profile if the authentication profile update was successful.

index.js 我已经定义了一个导出的函数来处理来自HTML表单的POSTed参数。下面的代码定义了另一个模块文件中的处理函数:

In index.js I have defined an exported function to deal with POSTed params from HTML forms. The code below defines the handler function in another module file:

 exports.auUpdateUserByEmail = (req, res) => {
  // This handler function will retrieve the POSTed params of user profile
  // and will attempt to update the existing user authentication as well as
  // the database profiles.
  //
  // This function accepts the following params:
  // 1. User email   // 2. Phone number   // 3. password   // 4. Display name
  // 5. Photo url   // 6. Disabled Flag
  //

  var db = admin.firestore();

  var uEmail = req.body.userEmail;
  var dName = req.body.displayName;
  var userId = "";

  var newuser = {
    displayName: dName
  }

  console.log("Email passed: " + uEmail);

  // Fetch the user UID by user email...
  res.write('User UID: ' + userId);
  console.log('User UID: ' + userId);

  // attempt to update the user authentication profile...
  return db.collection('Users').where('email', '==', email).get()
  .then(snapshot => {
    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == email)
        {
          userId = d.uid;
        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return res.end();

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return res.end();

  });
}

index.js ,我有以下导出定义:

In index.js, I have the following exports definition:

var appAuth = express();
//Here we are configuring express to use body-parser as middle-ware.
appAuth.use(bodyParser.urlencoded({ extended: false }));
appAuth.use(bodyParser.json());

appAuth.post('/updateUserByEmail', authusers.auUpdateUserByEmail);

exports.usersAuthFunctions = functions.https.onRequest(appAuth);

我必须说我能让它工作正常才能获得 uid ,更新auth配置文件,然后更新数据库配置文件,但它一直等待函数返回。

I have to say that I got it to work fine to get the uid, update the auth profile, and then update database profile, but it keeps on waiting for the function return.

感谢您的宝贵帮助。谢谢。

Appreciate your valuable help. Thanks.

我已经更新了下面的代码并执行了这些工作但是在HTTPS退出之前返回了一个空白页面承诺完成后会触发错误:写完后错误。

I have updated the code as below and it does the jobs but returns a blank page as the HTTPS exits before the promises are complete which fires "Error: write after end" error.

var fetch_uid = db.collection('Users').where('email', '==', uEmail).get()
  .then(snapshot => {
    // var userId = snapshot.data.uid;

    snapshot.forEach(doc => {
        var d = doc.data();
        console.log("doc.id: " + doc.id + " - d.email: " + d.email);
        if(d.email == uEmail)
        {
          userId = d.uid;

          res.write('User UID: ' + userId);
          console.log('User UID: ' + userId);

        }
    });

    return admin.auth().updateUser(userId, newuser);
  }).then(function(userRecord) {
    // The updating was successful... Attempt to update User Details in
    // database User Profile...
    console.log("User Updated Successfully. UID: " + userRecord.uid);
    retUid = userRecord.uid;

    // Create a reference to the Users Database...
    var docRef = db.collection('Users');

    // Update the user profile document.
    return docRef.doc(userRecord.uid).update(newuser);
  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    return;

  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);
    return;

  });

  res.end();


推荐答案

我之前关于 Firebase HTTP超时的云功能的回答可能会有所帮助这里:

A previous answer of mine on Cloud Functions for Firebase HTTP timeout might be of help here:


由HTTP请求触发的云功能需要以
结束,以结束发送() redirect() end(),否则
将继续运行并达到超时时间。

Cloud Functions triggered by HTTP requests need to be terminated by ending them with a send(), redirect(), or end(), otherwise they will continue running and reach the timeout.

从您的代码示例中,它看起来像您的 then(){} 承诺返回以 res.end()结尾,但整个函数从以下位置返回 Promise

From your code examples, it looks like your then(){} promise returns are ending with res.end(), but the entire function is returning the Promise from:

return db.collection('Users').where('email', '==', email).get()

这可能会阻止它在你想要的时候结束。使用HTTPS触发器,您不需要返回 Promise 来保持函数运行,只需要结果。

Which could be stopping it from ending when you want it to. With HTTPS triggers, you don't need to return a Promise to keep the function running, only a result.

尝试从此行中删除return语句:

Try removing the return statement from this line:

db.collection('Users').where('email', '==', email).get()

然后你只需要确保所有的退出路线(或终止点)以 res.end()或类似结束,因此目前您有2个终止点:

Then you just need to ensure that all exit routes (or termination points) end with res.end() or similar, so currently you have 2 termination points:

  }).then(result => {
    // everything went fine... return User UID as a successful result...
    res.write(userId);

    res.status(200).end();
  }).catch(function(error) {
    console.log("doc.update - Error updating user profile in database:", error);

    res.status(500).end();
  });

这篇关于Firebase函数返回并且promise不会退出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆