【问题标题】:Why does Firebase Cloud Function execute defined Promise为什么 Firebase Cloud Function 执行定义的 Promise
【发布时间】:2020-12-10 06:55:45
【问题描述】:

我正在尝试创建一个以后可以使用的 Promise。但是,该信息似乎无关紧要,因为 Promise 无需调用即可执行。 为什么会自动调用 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");
});

当我在本地运行 Firebase 函数并托管时,会在不调用 Promise 或调用云函数的情况下执行 Promise。当我调用云函数时,再次执行 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...

我根本不希望 Promise 运行。我只希望 Promise 在我调用 p() 时运行我发布的代码是正在运行的确切代码

【问题讨论】:

  • 你认为是不是 const p = new Promise(function (resolve) { ...... }) 不是被“调用”......它是 - 然后你继续说 when I call p()...... 但 be 是一个承诺,而不是一个功能- 所以“调用 p()”会导致错误 - 很惊讶你没有看到

标签: javascript firebase promise google-cloud-functions


【解决方案1】:
const p = function(){
      new Promise(function (resolve) {
      setTimeout(function () {
        console.log("server generating random number...");
        resolve(Math.random());
      }, 1000);
  })
};
p();

它是这样工作的。 也许是因为您已经定义了变量 .Promise 在程序加载时就像“P”的初始值一样。尝试使用不同的方法。

【讨论】:

    【解决方案2】:

    当你的代码执行new Promise,或者调用任何返回一个promise的方法时,这个promise的工作就开始了。您不必打电话给thencatch 就可以让它发挥作用。

    这不是 Cloud Functions 独有的。这正是 JavaScript 的工作方式。

    【讨论】:

    • 我没有那样做。如何在不执行的情况下存储一个 Promise 供以后使用?
    • 你不能。您可以改为存储一个要调用的函数,该函数会产生一个新的 Promise 来满足您的需求。
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 2020-11-13
    • 2023-03-25
    • 2019-01-16
    • 2020-03-13
    • 2021-05-02
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多