OGeek|极客世界-中国程序员成长平台

标题: ios - Swift PromiseKit : Equivalent to when() which executes sequentially? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:38
标题: ios - Swift PromiseKit : Equivalent to when() which executes sequentially?

我正在使用 PromiseKit 和 Swift,到目前为止它非常方便。他们提供的函数之一是 when(),它允许您拥有一个包含任意数量的 Promise 的数组,并且只有在所有 Promise 都完成后才执行某些操作。

但是,数组中的 Promise 是并行执行的。我还没有找到任何可以让我按顺序执行它们的功能。我尝试编写自己的递归函数,但它似乎没有按照它们在数组中的顺序执行 promise ,并且我偶尔会遇到“Promise deallocated”错误。请帮忙!

static func executeSequentially(promises: [Promise<Void>]) -> Promise<Void> {
    return Promise<Void> { fulfil, reject in
        var mutablePromises = promises
        if mutablePromises.count > 0 {
            mutablePromises.first!
                .then { _ -> Promise<Void> in
                    print("DEBUG: \(mutablePromises.count) promises in promise array.")
                    mutablePromises.remove(at: 0)
                    return executeSequentially(promises: mutablePromises)
                }.catch { error in
                    print("DEBUG: Promise chain rejected.")
                    reject(error)
            }
        } else {
            print("DEBUG: Promise chain fulfilled.")
            fulfil(())
        }
    }
}



Best Answer-推荐答案


这是一个扩展,它接受一组 Promise 并返回一个新的 Promise,其中所有单独的 Promise 链接在一起以串行运行。我已经修改了此处找到的版本以与 Swift 5/PromiseKit 7 alpha 一起使用:https://gist.github.com/kashifshaikh/416b9ffbd300eb680fad3641b6ec53ea

原作者随附的帖子可以在这里找到:https://medium.com/@peatiscoding/promisekit-chaining-3c957a8ace24

import Foundation
import PromiseKit

extension Promise {
  
  /// Returns a single Promise that you can chain to. Wraps the chains of promises passed into the array into a serial promise to execute one after another using `promise1.then { promise2 }.then ...`
  ///
  /// - Parameter promisesToExecuteSerially: promises to stitch together with `.then` and execute serially
  /// - Returns: returns an array of results from all promises
  public static func chainSerially<T>(_ promises:[() -> Promise<T>]) -> Promise<[T]> {
    // Return a single promise that is fulfilled when
    // all passed promises in the array are fulfilled serially
    return Promise<[T]> { seal in
      var outResults = [T]()
      
      if promises.count == 0 {
        seal.fulfill(outResults)
      } else {
        let finalPromiseromise<T>? = promises.reduce(nil) { (r, n) -> Promise<T> in
          return r?.then { promiseResult -> Promise<T> in
            outResults.append(promiseResult)
            return n()
          } ?? n()
        }
        
        finalPromise?.done { result in
          outResults.append(result)
          
          seal.fulfill(outResults)
        }.catch { error in
          seal.reject(error)
        }
      }
    }
  }
}

用法:

let serialSavePromises: [() -> Promise<Bool>] = allImages.map { image in
 return { [weak self] in
   guard let self = self else { return .value(false) }
      
   return self.saveImage(image)
 }
}
            
return Promise<[Bool]>.chainSerially(serialSavePromises)

关于ios - Swift PromiseKit : Equivalent to when() which executes sequentially?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48350305/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4