Swift 如何让另一个异步调用等待?
如果其中一个异步调用捕获到需要在继续其他调用之前先执行的条件,如何暂停另一个异步调用?根据下面的代码(简化),当makeRequest得到401时,它应该调用refreshSession并暂停其他调用,直到这个调用完成Swift 如何让另一个异步调用等待?,swift,queue,grand-central-dispatch,dispatch-queue,Swift,Queue,Grand Central Dispatch,Dispatch Queue,如果其中一个异步调用捕获到需要在继续其他调用之前先执行的条件,如何暂停另一个异步调用?根据下面的代码(简化),当makeRequest得到401时,它应该调用refreshSession并暂停其他调用,直到这个调用完成 let refreshSessionDispatchQueue = DispatchQueue(label: "refreshSession") var refreshSessionJobQueue: [APIRequest] = [] // This fu
let refreshSessionDispatchQueue = DispatchQueue(label: "refreshSession")
var refreshSessionJobQueue: [APIRequest] = []
// This function will be called by each of APIs that got 401 error code
private func refreshSession(errorCode: String? = nil, request: APIRequest) {
refreshSessionDispatchQueue.async {
self.refreshSessionJobQueue.append(request)
}
// The idea is, after all job appended to the jobQueue, let says after 1', it will call another function to execute another job
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.executeRefreshSessionJobQueue()
}
}
// This is to execute refreshSession, and if it's succeed, all job on the jobQueue will be re-executed
private func executeRefreshSessionJobQueue() {
DispatchQueue.main.async {
let readyToRefreshSessionJobQueue = self.refreshSessionJobQueue
if self.refreshSessionJobQueue.count > 0 {
self.refreshSessionJobQueue = []
self.refreshSession { [weak self] succeed in
if succeed {
for job in readyToRefreshSessionJobQueue {
self?.makeRequest(baseURL: job.baseURL, endpoint: job.endpoint, method: job.method, encoding: job.encoding, headers: job.headers, params: job.params, customBody: job.customBody, completion: job.completion)
}
self?.refreshSessionJobQueue = []
} else {
// And if it's failed, all the job should be removed and redirect the page to the login page
self?.refreshSessionJobQueue = []
ErrorHandler.relogin()
}
}
}
}
}
如果在获取401时需要重试API,可以尝试使用Alamofire的RequestInterceptor中的RequestRetrier。它基本上会重试遇到错误的请求,例如您的案例中的401
可以找到实现的完整示例。希望有帮助,干杯 在这个场景中,看起来您不希望同时执行它们,而是按顺序执行(等待第一个请求完成,然后再执行下一个请求,依此类推)。您在示例中调用它们的方式将“同时”启动它们在后端调用返回之前,您已经过了要等待的注释在现实生活中,您所有的请求都返回401,并且没有理由暂停任何请求,因此我对@Goergisn很感兴趣。您应该使请求堆叠/排序,逐个运行请求,并在需要时重新创建会话。对于并发请求,您可以在第一次失败时创建新会话,但之后应该再次重新创建所有请求。