0

I want to return value from nested function in javascript.

this is my code:

export const getArtistMusics = (id) => {
    return cheerioInit(`https://mrtehran.com/artist/${id}`).then(($) => {
        const SECTION = $('.musicbox-tracks .musicbox-item')
        let musics = []

        SECTION.each((i, elem) => {
            return (async () => {
                const PAGE_LINK = $(elem).attr('mtp-data-url')
                return await getMusic(PAGE_LINK)
            })()
        })

        return musics
    })
}

as you see I returned an async IIFE function, but I don't know how to return the value (promise) outside of SECTION.each block.

I want to push values to musics array and then return it.

What is the solution for this situation?

jeprubio
  • 17,312
  • 5
  • 45
  • 56
ShaSha
  • 589
  • 3
  • 9
  • 24
  • `each`/`forEach` and promises rarely work well together - try using a for loop inside an async function - or `.map` and Promise.all are also a good combination – Jaromanda X Mar 01 '20 at 22:25
  • replace the code after `const SECTION = ....` with `return Promise.all(Array.from(SECTION, elem => getMusic($(elem).attr('mtp-data-url'))));` – Jaromanda X Mar 01 '20 at 22:28
  • You're returning a promise on line 2. You'll need to `await` that stuff if you want to return a value. – JayB Mar 01 '20 at 22:31
  • Any value returned from a function called by [`.each()`](https://api.jquery.com/each/) is discarded. The `SECTION.each` function needs to push promises into `music` and then, after the each loop finishes, `await Promise.all(music)`; – traktor Mar 01 '20 at 23:29
  • @JaromandaX @JayB @traktor53 ```each``` is built in function for cheerio.js library – ShaSha Mar 02 '20 at 07:49
  • yes, @ShaSha - and it still isn't *compatible* with Promises - did you even try my code suggestion? – Jaromanda X Mar 02 '20 at 07:51
  • @JaromandaX thanks it works – ShaSha Mar 02 '20 at 16:51

0 Answers0