How to return value from Promise in swift

2k Views Asked by At

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?

1

There are 1 best solutions below

0
Romulan233 On

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)
        }
    })
}