Why does Firebase Cloud Function execute defined Promise

Viewed 73

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

2 Answers

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.

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. Try Using a different approach.

Related