菜鸟教程小白 发表于 2022-12-11 19:38:07

ios - Swift PromiseKit : Equivalent to when() which executes sequentially?


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

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

<pre><code>static func executeSequentially(promises: ) -&gt; Promise&lt;Void&gt; {
    return Promise&lt;Void&gt; { fulfil, reject in
      var mutablePromises = promises
      if mutablePromises.count &gt; 0 {
            mutablePromises.first!
                .then { _ -&gt; Promise&lt;Void&gt; in
                  print(&#34;DEBUG: \(mutablePromises.count) promises in promise array.&#34;)
                  mutablePromises.remove(at: 0)
                  return executeSequentially(promises: mutablePromises)
                }.catch { error in
                  print(&#34;DEBUG: Promise chain rejected.&#34;)
                  reject(error)
            }
      } else {
            print(&#34;DEBUG: Promise chain fulfilled.&#34;)
            fulfil(())
      }
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这是一个扩展,它接受一组 Promise 并返回一个新的 Promise,其中所有单独的 Promise 链接在一起以串行运行。我已经修改了此处找到的版本以与 Swift 5/PromiseKit 7 alpha 一起使用:<a href="https://gist.github.com/kashifshaikh/416b9ffbd300eb680fad3641b6ec53ea" rel="noreferrer noopener nofollow">https://gist.github.com/kashifshaikh/416b9ffbd300eb680fad3641b6ec53ea</a> </p>
<p>原作者随附的帖子可以在这里找到:<a href="https://medium.com/@peatiscoding/promisekit-chaining-3c957a8ace24" rel="noreferrer noopener nofollow">https://medium.com/@peatiscoding/promisekit-chaining-3c957a8ace24</a> </p>
<pre><code>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&lt;T&gt;(_ promises:[() -&gt; Promise&lt;T&gt;]) -&gt; Promise&lt;&gt; {
    // Return a single promise that is fulfilled when
    // all passed promises in the array are fulfilled serially
    return Promise&lt;&gt; { seal in
      var outResults = ()
      
      if promises.count == 0 {
      seal.fulfill(outResults)
      } else {
      let finalPromise:Promise&lt;T&gt;? = promises.reduce(nil) { (r, n) -&gt; Promise&lt;T&gt; in
          return r?.then { promiseResult -&gt; Promise&lt;T&gt; in
            outResults.append(promiseResult)
            return n()
          } ?? n()
      }
      
      finalPromise?.done { result in
          outResults.append(result)
         
          seal.fulfill(outResults)
      }.catch { error in
          seal.reject(error)
      }
      }
    }
}
}
</code></pre>
<p>用法:</p>
<pre><code>let serialSavePromises: [() -&gt; Promise&lt;Bool&gt;] = allImages.map { image in
return { in
   guard let self = self else { return .value(false) }
      
   return self.saveImage(image)
}
}
            
return Promise&lt;&gt;.chainSerially(serialSavePromises)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Swift PromiseKit : Equivalent to when() which executes sequentially?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48350305/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48350305/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Swift PromiseKit : Equivalent to when() which executes sequentially?