简体   繁体   English

axios async await Cloud Function 在 axios 完成 post 请求之前返回

[英]Axios async await Cloud Function returning before axios completes post request

I have a react app, with a message page.我有一个带有消息页面的 React 应用程序。 The message page allows the user to submit a message.消息页面允许用户提交消息。 The submission process sends the message info to a Cloud Function deployed on Firebase Functions (Google Cloud).提交过程将消息信息发送到部署在 Firebase Functions (Google Cloud) 上的 Cloud Function。 The function responds with an object like this:该函数以这样的对象响应:

{
    success: true,
    message: 'Your message has been sent.'
}

This is the cloud function:这是云函数:

 const functions = require('firebase-functions') const admin = require('firebase-admin') admin.initializeApp() const fs = admin.firestore() const axios = require('axios') exports.sendMessage = functions.https.onCall(async (input) => { try { let outcome = await axios({ method: 'post', url: 'https://recaptcha.google.com/recaptcha/api/siteverify', params: { secret: --redacted--, response: input.recaptchaToken } }) outcome.data.success && fs.collection("messages").add({ timestamp: admin.firestore.FieldValue.serverTimestamp(), name: input.name, email: input.email, message: input.message }) return outcome.data.success ? { success: true, message: 'Your message has been sent.' } : { success: false, message: `Your message failed. You're a robot.` } } catch (error) { console.error('Cloud Function error:', error) return { success: false, message: 'Your message failed. Try again later.' } } })

However, it isn't working as intended.但是,它没有按预期工作。 The message successfully writes to Firestore, however the object I receive back is success: false, message: 'Your message failed. Try again later.''消息成功写入 Firestore,但是我收到的对象是success: false, message: 'Your message failed. Try again later.'' success: false, message: 'Your message failed. Try again later.''

The error I get from logging on Cloud Function is this:我从登录 Cloud Function 得到的错误是这样的:

ReferenceError: data is not defined
at exports.testSendMessage.functions.https.onCall

... which implies that the function isn't waiting for axios to resolve with a response (even though it does later), and is instead continuing on with the function, resulting in the error. ...这意味着该函数不会等待 axios 解析响应(即使它稍后会这样做),而是继续执行该函数,从而导致错误。

What is going on?到底是怎么回事?

ReferenceError: data is not defined is telling you that outcome.data is undefined. ReferenceError: data is not defined告诉你outcome.data是未定义的。 You should do more logging to determine why outcome is something other than what you expect.你应该做更多的日志来确定为什么outcome不是你期望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM