I am using snippet from this page marked as MediaWiki JS in my script:
const params = {
action: "parse",
page: stronaDyskusji,
prop: "wikitext",
section: index_sekcji,
};
const api = new mw.Api();
api.get(params).done((data) => {
console.log(data.parse.wikitext["*"]);
});
everything work fine and i can see data in console. But when I want to do this like that in order to process data it returns undefined.
var zwrot;
const params = {
action: "parse",
page: stronaDyskusji,
prop: "wikitext",
section: index_sekcji,
};
const api = new mw.Api();
api.get(params).done((data) => {
zwrot = data.parse.wikitext["*"];
});
console.log(zwrot);
Can you tell me pleas why or give me link to article, so i can learn myself how to work with this kind of data?
api.get().done()
is probably asynchronousMeans it takes either a callback function or it returns a promise that needs to be resolved. In your case the function takes a callback function which gets called once api.get().done()
has finished processing. Callbacks are often used to continue code execution after an asynchronous operation has completed (like in this case).
api.get(params).done((data) => {
console.log(data.parse.wikitext["*"]);
});
In your first code example, you are logging inside the callback function, means it will log after api.get().done()
has finished.
var zwrot;
api.get(params).done((data) => {
zwrot = data.parse.wikitext["*"];
});
console.log(zwrot);
In your second example you are trying to log the value of zwart
before the callback function has been triggered. Therefore, no value has been assigned to zwart
yet. So it logs undefined
( Read more about asynchronous )