How to get Content ID in a View (.hbs file), or how does getContext() returns it?

I am building a Confluence Cloud App with Connect. I want to get the Page ID (Content ID) of the page, where the Macro is put on. I’m working in the View-Folder of my Connect-App in a .hbs-file.

I can get the ID by using getContext(), but I can’t put it in a variable for later usage, because of the scope.

Like this I can see the ID in the console:

AP.context.getContext(function(response) {
    console.log = response.confluence.content.id;
});

But what I really need would be something like this (which doesn’t work):

var pageID;
AP.context.getContext(function(response) {
    pageID = response.confluence.content.id;
});
console.log(pageID);

I need to somehow return the ID via the callback function? How can I do it?

Or is there a simpler way? I could only find this resource: Context

AP.context.getContext can be used with a callback as you did above. It also returns a promise, and can be used like this:

(async function() {
   context = await AP.context.getContext();
   console.log('context', context);
 })();

or promise and resolve/reject.

Thank you for the tip, I did it like this now:

(async function() {
    var context = await AP.context.getContext();
    return context.confluence.content.id;
})().then(function(pageID) {
    console.log("pageID", pageID);
});

I can work in the unnamed function in the .then() part now, but maybe it’s a stupid question, but is there a possibility to get the result (the pageID) out of the scope of that unnamed function?
I see… I need to read about async JavaScript…

Your earlier code already made the pageID available outside of the callback. The problem however is that you don’t know when the callback returns (when the console.log runs, it has not yet returned).
Reading up on callbacks and promises should help.