[英]Why does Firebase Cloud Function execute defined Promise
I'm trying create a Promise that I can use later.我正在尝试创建一个稍后可以使用的 Promise。 However, that information seems irrelevant because the Promise executes without invocation.
但是,该信息似乎无关紧要,因为 Promise 无需调用即可执行。 Why is the Promise invoked automatically?
为什么会自动调用 Promise?
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.当我运行 Firebase 函数并在本地托管时,执行 promise 而不调用 promise 或调用云 ZC141145268C163。 When I invoke the cloud function, the Promise is executed again.
当我调用云 function 时,再次执行 Promise。
$ 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.我不希望 Promise 能够运行。 I would only to expect the Promise to run when I call
p()
The code I posted is the exact code that is running我只希望 Promise 在我调用
p()
时运行 我发布的代码是正在运行的确切代码
The moment your code executes new Promise
, or call any method that returns a promise, the work of that promise has been started.当您的代码执行
new Promise
或调用任何返回 promise 的方法时,该 promise 的工作已经开始。 You don't have to call then
or catch
on a promise to get it to do work.你不必打电话或
catch
then
来让它工作。
This is not unique to Cloud Functions.这不是 Cloud Functions 独有的。 This is just the way JavaScript works.
这就是 JavaScript 的工作方式。
const p = function(){
new Promise(function (resolve) {
setTimeout(function () {
console.log("server generating random number...");
resolve(Math.random());
}, 1000);
})
};
p();
It works like this.它是这样工作的。 Maybe it is because you have defined the variable.The promise is acting like the Initial value for 'P' as the program loads.
也许是因为您已经定义了变量。promise 在程序加载时就像“P”的初始值一样。 Try Using a different approach.
尝试使用不同的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.