Save in Repo from task

I fetch data from a task and want to store the data in repo.
This is my code:

function saveToRepo(item) {

    try {
        const result = contentLib.create({
            name: 'market_news_' + item.guid.contents,
            displayName: item.title,
            contentType: `${}:marketNews`,
            parentPath: '/',
            data: item
        })'Content created with id ' + result._id);

    } catch (e) {
        if (e.code == 'contentAlreadyExists') {
            log.error('There is already a content with the name %s', item.title);
        } else {
            log.error('Unexpected error: ' + e.message);
  'item: ' + JSON.stringify(item, null, 2));


I call this from a different context, saveToRepo(item));, where item is a JSON-Object which fits in the content-type definition.

EDIT: When I log the current context inside saveToRepo, shouldn’t I get the context set by (= CTX)?

This ends up in the following errors:
from saveToRepo(item)

 ERROR org.lienas.webpack - (/tasks/fetchnews/fetchnews.js) Unexpected error: null

and then:

 ERROR c.e.x.i.task.script.NamedTaskScript - Error executing named task [org.lienas.webpack
:fetchnews] 'News abrufen' with id 4dfc271c-c0b7-4de3-bf73-3fc92a5d1b6e: Cannot cast jdk.nashorn.internal.runtime.Undefined to java.util.concurrent.Callable
java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.runtime.Undefined to java.util.concurrent.Callable 
        at java.base/java.lang.Class.cast(
        at jdk.scripting.nashorn.scripts/jdk.nashorn.internal.scripts.Script$Recompilation$1284$1231AA$context.L:1#run(org.lienas.webpack:/lib/xp/context.js:31)

When I run without defining the context, I only get the first error!

I made some further investigations !
I changed the permission for the repo to full access to role:system.everyone.
Now it works.
So, why does the context change not work ?? I refactored the code exactly to the provided examples:

const runInContext = function (callback) {
    let result;
    try {
        result ={
            principals: ["role:system.admin"],
            repository: 'com.enonic.cms.default',

        }, callback);
    } catch (e) {'Error: ' + e.message);

    return result;

Then I call runInContext(saveToRepo(item));

with saveToRepo as posted before!

Found solution myself … and like mostly … the solution is simple and logic:
I have to pass a callback-function and not execute the function, like I did.
I normally use an arrow-function for this, like the following:

runInContext(() => {

That also explains, why context is no changed.


Great that you managed to find a solution yourself. Executing the callback before it’s passed to the function would of course result in the incorrect behaviour you experienced.