2

저는 Firebase 세계에서 아직 초보자입니다. 아래 코드에서 문제가 무엇인지 알아 내려고 노력하고 있지만 모든 가능한 방법으로 실패했습니다.Firebase 함수 반환과 약속이 함수를 종료하지 않습니다.

코드는 데이터베이스의 사용자 프로필에서 uid을 검색 한 다음이를 사용하여 인증 프로필을 업데이트 한 다음 인증 프로필 업데이트가 성공한 경우 다시 데이터베이스 프로필을 업데이트합니다.

index.js에서 HTML 양식의 POST 된 매개 변수를 처리하기 위해 내 보낸 함수를 정의했습니다. 아래의 코드는 다른 모듈 파일 핸들러 함수를 정의

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, 나는 다음과 같은 수출 정의가 : 나는 그것이를 얻기 위해 잘 작동 할 수있어 '라고해야

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 프로필을 업데이트 한 다음 데이터베이스 프로필을 업데이트하지만 함수가 반환되기를 기다립니다.

귀하의 소중한 도움에 감사드립니다. 감사.


나는 아래의 코드를 업데이트하고 작업을 수행하지만 약속하기 전에 HTTPS가 종료 "오류 : 종료 후 쓰기"발사되는 완료로 빈 페이지를 반환 오류가 발생했습니다.

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(); 
+0

가능한 복제 (https://stackoverflow.com/questions/47154257/cloud-functions-for-firebase-http-timeout) – Grimthorr

답변

1

Cloud Functions for Firebase HTTP timeout에 내 이전의 대답은 여기에 도움이 될 수 있습니다 코드 예제에서

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 출처 :

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

원하는 경우 언제 끝내겠습니까? 그것까지. HTTPS 트리거를 사용하면 함수를 계속 실행하기 위해 Promise을 반환 할 필요가 없으며 결과 만 표시됩니다.

이 라인에서 return 문을 제거하십시오 : 당신이 개 종료 지점이 때문에 현재

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

그런 다음 당신은 그냥 모든 출구 경로 (또는 종료 지점) res.end() 또는 유사한로 끝나는 있는지 확인해야합니다 :

}).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(); 
    }); 
[중포 기지 HTTP 시간 초과 클라우드 기능]의
+0

나는 그것이를 얻을 수있었습니다 일을 끝내고 그 기능을 끝내라. 그것보다 더 빨리 함수를 종료하고 약속이 아직 보류 중이고 res.write가 쏴서 오류를 일으키는 것입니다! –

+0

아, 내가 편집에 열중했을 수도 있으므로'db.collection ('Users') [...]'줄에서'return' 만 제거하면됩니다. – Grimthorr

+0

나중에,하지만 여전히 ... 나는 somethings 쓸 필요가 ... 반환 된 페이지가 비어와 나는 "오류 : db.collection의 약속 전에 함수가 존재하기 때문에 끝내기"를 얻을 ... get () 반환!http 함수가 존재하기 전에 이러한 약속이 끝날 때까지 기다리는 법? –

관련 문제