Promise & Then on Angular TypeScript {N}

android

#1

Hi,
I’m a newcomer to TypeScript, so I’m experiencing problems with my promise coding.
What I need is running this.otherFunction() when the getFavs is resolved.
The getFavs should return an array of Song objects. The getFavs is subscribed to a tested service.
So I get the favs but I’m not getting the otherFunction execution :frowning:


 ngOnInit(): void { this.loadAll()}

loadAll(cache = false) {
    this.getFavs()
        .then(
            (favs: Array<Song>) => {
                    this.x= this.otherFunction();
            },

            (error) => {
                console.log("errrrrrt");
            }
        );
}


getFavs(): Promise<Array<Song>> {

    return new Promise<Array<Song>>(
        (resolve, reject) => {
            const flist = [];
            this.subsFavs = this.songListService.load("favs");
            this.subsFavs.subscribe((favs) => {
                favs.forEach((fav) => {
                    flist.push(
                        new Song(fav.song.id,
                            fav.song.name,
                            fav.song.artist,
                            fav.song.cover,
                            fav.song.album,
                            fav.song.year)
                    );
                });
               this.favsongList = flist;
                return flist;
            });

        });
}

#2

That was a small mistake. You forgot to do a resolve from your promise, your promise code should look like this,

getFavs(): Promise<Array<Song>> {

    return new Promise<Array<Song>>(
        (resolve, reject) => {
            const flist = [];
            this.subsFavs = this.songListService.load("favs");
            this.subsFavs.subscribe((favs) => {
                favs.forEach((fav) => {
                    flist.push(
                        new Song(fav.song.id,
                            fav.song.name,
                            fav.song.artist,
                            fav.song.cover,
                            fav.song.album,
                            fav.song.year)
                    );
                });
               this.favsongList = flist;
               resolve(flist);
            });

        });
}

just do a resolve instead of returning and you should be good to go :slight_smile:


#3

Fantastic! Resolve instead Return :wink: Thanks!