Error calling Document.flatten()

I’m in the process of learning how to write UXP plugins, and I’m getting an error that is probably simple to explain, but I’m having trouble figuring it out.

I’d like to call the flatten() method on the active document, so I first tried this:

const app = require("photoshop").app;
const { executeAsModal } = require("photoshop").core;
 
try {
       await executeAsModal( app.activeDocument.flatten, {"commandName": “Flatten”});
}  catch(e) {console.log(e);}

That throws an error:

TypeError: Cannot read properties of undefined (reading 'id’)

However, if I use batchPlay it works perfectly:

const app = require("photoshop").app;
const { executeAsModal } = require("photoshop").core;
const { batchPlay } = require("photoshop").action;

try {
    await executeAsModal( async () => {
        const result = await batchPlay(
          [
             {
                _obj: “flattenImage”,
                _options: {
                   dialogOptions: “dontDisplay”
                }
             }
          ],
          {}
       )
    }, {"commandName": “Flatten”});
} catch(e) {console.log(e);}

I’d rather use the object methods in the API if they exist rather than use batchPlay, but I haven’t been able to get Document.flatten() to work. Am I missing something? I’m using manifestVersion 5 with PS version 24.7.2.

Thanks!

I might be wrong, but I don’t think you can pass the document’s flatten method directly as targetFunction of executeAsModal. This doc goes into the specifics of what arguments need to be passed. Strictly speaking the target function is supposed to have a specific signature, which UXP will call passing execution context. The reason your second version is working I think is because you’re passing an arrow expression as target function (i.e. you are wrapping your actual function call). Have you tried something similar with the API method, i.e. not directly calling it but call it inside of the arrow expression (and awaiting return)? Something like this…

try {
    await executeAsModal( async () => {
        await app.activeDocument.flatten();
    }, {"commandName": “Flatten”});
} catch(e) {console.log(e);}

Aha! OK, I get it now. I hadn’t appreciated that targetFunction has an explicit signature, your version worked perfectly for me.