-1

I have a function like this

    func fetchPokemons() -> [Pokemon] {
    var pokemons : [Pokemon] = []
    service.fetchPokemons().done{ (newPokemons) in
        pokemons += newPokemons.pokemons!
        print(pokemons)
    }.catch { (error) in
        print(error)
    }
    print(pokemons)
    return pokemons
}

I need to get pokemons and then put them into array. My problem is obvious. Promises are asynchronous that's why my function returns empty array. .then function used to return another Promise and .done returns Void. So how should I write a completion handler to return filled array of Objects?

Ivanius
  • 109
  • 1
  • 2
  • 9
  • 6
    Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Joakim Danielson Feb 20 '21 at 11:13
  • Yes. Thanks for your answer and sorry for my bad question – Ivanius Feb 20 '21 at 11:54

1 Answers1

0

This is the function that can return the promise of type UIImage.

func getImageWithPromise() -> Promise<UIImage> {
    return Promise<UIImage>(on: .global(qos:.background), { (fulfill, reject) in
        URLSession.shared.dataTask (with: url) { data, response, error in
            if error != nil {
                reject(error)
                return
            }
            fulfill(data)
        }
    })
}
karel
  • 5,489
  • 46
  • 45
  • 50
Romulan233
  • 13
  • 2