0

This is a function in Javascript that I need for checking an Angular service by subscribe if it contains an array or not but the the return value is undefined because the function doesn't change the variable value inside the subscribe.

    function checkAvailableBonus() {
        var dataSize = 0;
        var returnValue = "false";
        window.angularComponentRef.component.slotsBonusesService.getPlayerAvailableBonuses().subscribe(function (data) {
            dataSize = data.length;
            if (dataSize !== 0) {
                returnValue = "true";
            } else {
                returnValue = "false";
            }

        });
        return (returnValue);
    }
    checkAvailableBonus();

I except the function to return "true"/"false" after the subscribe was done.

Yuval Or
  • 11
  • 2
  • This is question asked multiple times, subscribe is asynchronous. – jcubic Sep 08 '19 at 09:19
  • Just a note that Observables are not asynchronous per se. Only if we execute micro or macro tasks within the stream it becomes async. A `of(1, 2, 3)` for example would not be async. – ChrisY Sep 08 '19 at 09:32

1 Answers1

1

Your function installs a callback (the subscribe(function (data) bit), and then immediately returns returnValue, without waiting for the callback to execute, so you'll always return "false".

Instead, use a Promise:

function checkAvailableBonus() {
    return new Promise(resolve => {
        window.angularComponentRef.component.slotsBonusesService.getPlayerAvailableBonuses().subscribe(function (data) {
            const dataSize = data.length;
            if (dataSize !== 0) {
                resolve("true");
            } else {
                resolve("false");
            }

        });
    });
}
checkAvailableBonus().then(result => console.log(result));
user4520
  • 3,401
  • 1
  • 27
  • 50