Document Server version:8.2
Hi support team, I would like to know how to return data in callCommand with async function. I tried to do that but the result i got is an empty object instead of an object with data:3 as expected.
Here is my code example:
window.Asc.plugin.callCommand(
async () => {
const result = 3;
console.log(result);
return { data: result };
},
(result: any) => {
console.log(result);
}
);
Hello @ZangHoang
It really depends on where you’d like to get callback. You see, async functions return promise object instead of a string or number, hence you can only get callback inside the async function, i.e. you cannot pass it to the callCommand callback.
To demonstrate I’ve got this example:
window.Asc.plugin.callCommand(function () {
const asyncFn = async () => {
const res = 3;
console.log("Console Log: ", res + 1 ); // Here I've added 1 to demonstrate the it returns res separately
return res;
}
asyncFn().then(res => {
console.log("Returned: ", res + 2) ; // Added 2 to the res to demonstrate the result being separate from previous one
});
});
First, I’ve declared async function, i.e. not calling anonymous async function like in your example.
Then I am reusing result that it returns by calling the asyncFn
function again with .then
operator. That way function passes first result to the second “round” of execution.
Since callCommand does not naturally return callback value and onCommandCallback must be used for that, you might try getting callback that way. However, callCommand works only with strings and numbers, it cannot operate with objects. Since async function returns promise, which is an object, you cannot pass it outside the callCommand method.
Usage of async functions purely depends on the goal you are trying to achieve. In general, you can use them, but I don’t see the reason to use it inside callCommand.
1 Like