javascript - Why does Firebase Cloud Function execute defined Promise
问题描述
I'm trying create a Promise that I can use later. However, that information seems irrelevant because the Promise executes without invocation. Why is the Promise invoked automatically?
const functions = require("firebase-functions");
const p = new Promise(function (resolve) {
setTimeout(function () {
console.trace("server generating random number...");
resolve(Math.random());
}, 1000);
});
module.exports.MyCustomFunction = functions.https.onRequest(function (req, res) {
res.send("hello world");
});
When I run the Firebase functions and hosting locally, the promise is executed without invoking the promise or invoking the cloud function. When I invoke the cloud function, the Promise is executed again.
$ firebase serve --only functions,hosting
i functions: Watching "/code/project" for Cloud Functions...
i hosting: Serving hosting files from: dist/client
✔ hosting: Local server: http://localhost:5000
✔ functions[MyCustomFunction]: http function initialized (...).
> server generating random number...
...
i functions: Finished "MyCustomFunction" in ~1s
> server generating random number...
I do not expect the Promise to run at all. I would only to expect the Promise to run when I call p()
The code I posted is the exact code that is running
解决方案
The moment your code executes new Promise
, or call any method that returns a promise, the work of that promise has been started. You don't have to call then
or catch
on a promise to get it to do work.
This is not unique to Cloud Functions. This is just the way JavaScript works.
推荐阅读
- c - 重新分配具有无效下一个大小错误的动态无符号字符数组时出错
- stripe-payments - 如何将测试余额添加到条带测试帐户以测试 API 集成
- r - ggplot2 - 自定义刻面位置
- python - Seaborn 色调和尺寸图例
- oracle - 打开文件时目录路径无效
- javascript - 如何在 react--modal-video 中显示不同的链接?
- r - 基于另一个没有长数据的数据框创建 NA
- javascript - 当不喜欢记录我的nodejs时,无法在将标头发送到客户端后设置标头
- r - boot.ci 错误,由于数据变化太小?
- c# - MonogDB C# 驱动程序 LINQ 查询在按 _id 过滤时不起作用