我正在寻找开发同步服务,当用户拉动刷新时会触发该服务。此同步服务将对服务器执行多个请求。每次API调用完成后,如何手动触发PromiseKit
承诺?承诺的回调正在被立即召唤。
//MyViewController.swift
func refresh(sender: AnyObject){
var promise = syncService.syncFromServer()
promise.then{ response
//This is called immediately, and I need it to wait until the sync is complete
refreshControl?.endRefreshing()
tableView.reloadData()
}
}
//SyncService.swift
func syncFromServer() -> Promise<AsyncResult>{
let promise = Promise(value: AsyncResult)
var page = 1
//Multiple API calls
//let request1 = ...
//let request2 = ...
//let request3 = ...
//How do I tell the returned promise to trigger the associated callbacks after the last API requests has been completed?
//Another scenario I need to handle is when the amount of requests is not known ahead of time.
while(true){
var response = makeAnApiCall(page)
//if the response body says no more data is available, break out of the while loop, and tell any promise callbacks to execute.
//if(noMoreData){
// how do I perform something like
// promise.complete //This line needs to tell the `then` statement in `MyViewController` to execute.
// break
//}else{
// do something with response data
//}
page = page + 1
}
return promise
}
答案 0 :(得分:1)
下面我提供了一个示例,说明在所有syncService调用运行后,如何结束刷新和更新tableView。查看有关使用'when'的PromiseKit文档。
func refresh(sender: AnyObject){
syncService.syncFromServer().then { response in
refreshControl?.endRefreshing()
tableView.reloadData()
}
}
//SyncService.swift
func syncFromServer() -> Promise<Void> {
let request1 = methodReturningPromise1()
let request2 = methodReturningPromise2()
return when(fulfilled: [request1, request2])
}
private func methodReturningPromise1() -> Promise<Void> {
return syncService.someDataCall().then { response -> Void in
//do something here
}
}