gpt4 book ai didi

json - 如何在 Cloud Functions for Firebase 中使 HTTP 请求异步/等待?

转载 作者:行者123 更新时间:2023-12-05 06:36:24 24 4
gpt4 key购买 nike

我正在尝试使用 Cloud Functions for Firebase 通过 async/await 进行 JSON 调用。

知道如何修复以下代码吗?我的计划是 Blaze。

我的灵感是https://www.valentinog.com/blog/http-requests-node-js-async-await/

部署错误

functions[setDetails]: Deployment error.

const getDetails = async url => {

SyntaxError: Unexpected identifier at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at require (internal/module.js:20:19) at getUserFunction (/var/tmp/worker/worker.js:378:24)

INDEX.JS

'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Promise based HTTP client for the browser and node.js
const axios = require('axios');

admin.initializeApp(functions.config().firebase);
const url = 'https://api.xxxx.com/json?partnumber=';
const getDetails = async url => {
try {
const response = await axios.get(url);
const data = response.data;
const getDet = data.results[0].details;
return getDet;
} catch (error) {
console.log(error);
return error;
}
};
exports.setDetails = functions.database.ref('/equipment/{pushId}').onWrite((event) => {
const post = event.data.val();
if (post.details){ return };
const number = post.number;
const details = getDetails(url + number);
admin.database().ref('/equipment/{pushId}').push({number: number, details: details});
});

PACKAGE.JSON

{
"name": "look-at-details",
"description": "bla bla bla",
"dependencies": {
"axios": "^0.18.0",
"firebase-admin": "^5.9.1",
"firebase-functions": "^0.8.1"
},
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase experimental:functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
}
}

最佳答案

Cloud Functions 尚不支持 async/await。 Cloud Functions 运行节点 6,它不使用支持异步/等待的 JavaScript 版本。部署失败,因为它不知道 async 关键字。

相反,您可以将项目初始化为使用支持异步/等待的 TypeScript。 Firebase CLI 会自动将您的代码转换为使用 Promises 实现异步/等待的 ES6。

关于json - 如何在 Cloud Functions for Firebase 中使 HTTP 请求异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com