无法将类型'Promise <Void>'的返回表达式转换为返回类型'Promise <JSON>'Swift

时间:2019-06-25 23:05:16

标签: swift asynchronous promisekit

我对PromiseKit还是陌生的,在获取Promise的价值时遇到了麻烦。最终目标是使异步调用解析为JSON数组。当前,编译器在抱怨:

Cannot convert return expression of type 'Promise<Void>' to return type 'Promise<JSON>'

我很困惑,还没有找到看起来像我要去的解决方案。谁能看到我要去哪里错了?

这是get方法,该方法调用我的后端以获取Json数据。

public func get(_ url: URL) -> Promise<JSON> {
    return Promise<JSON> { resolver -> Void in

      Alamofire.request(url)
        .validate()
        .responseJSON { response in
          switch response.result {
          case .success(let json):
            let json = JSON()
            if let data = response.data {
              guard let json = try? JSON(data: data) else {
                resolver.reject("Error" as! Error)
                return
              }
              resolver.fulfill(json)
            }
          case .failure(let error):
            resolver.reject(error)
          }
      }
    }
  }

以下是使用上述方法的方法:

public func fetchAllocations() -> Promise<JSON> {
    let url: URL = createAllocationsUrl()
    var allocations = JsonArray()

    let responsePromise = httpClient.get(url).done { (fetchedJSON) in
      let fetchedAlloc: JsonArray = JSON(fetchedJSON).array ?? []
      if fetchedAlloc.count > 0 {

        let eid = "9b0e33b869"
        let previousAlloc = self.store.get(eid)

        if let previousAllocations = previousAlloc {
          if previousAllocations.count > 0 {
            allocations = Allocations.reconcileAllocations(previousAllocations, allocations)
          }
        }
        self.store.set(eid, val: allocations)
        self.allocationStatus = AllocationStatus.RETRIEVED

        if self.confirmationSandbagged {
          self.eventEmitter.confirm(allocations)
        }
      }
    }
    return responsePromise
  }

然后在我的视图控制器的按钮中,按如下方式执行该功能:

    // This should be a Promise<JSON> that I can resolve and fulfill
    let promise = alloc.fetchAllocations().done { (json) in
      self.allocations = [json]
    }
    let eid = "9b0e33b869"
    let cached = store.get(eid)
    print("YOUR FETCHED ALLOCATION: \(String(describing: self.allocations))")
    print("YOUR CACHED ALLOCATION: \(String(describing: cached))")

当我进入打印报表时,每次都为零。

1 个答案:

答案 0 :(得分:0)

 public func fetchAllocations() -> Promise<[JSON]> {

    return Promise { resolve in
      let url = self.createAllocationsUrl()

      let strPromise = HttpClient.get(url: url).done { (stringJSON) in
        var allocations = JSON.init(parseJSON: stringJSON).arrayValue
        let previous = self.store.get(self.participant.getUserId())

        if let prevAlloc = previous {
          if Allocator.allocationsNotEmpty(allocations: prevAlloc) {
            allocations = Allocations.reconcileAllocations(previousAllocations: prevAlloc, currentAllocations: allocations)
          }
        }

        self.store.set(self.participant.getUserId(), val: allocations)
        self.allocationStatus = AllocationStatus.RETRIEVED

        if (self.confirmationSandbagged) {
          self.eventEmitter.confirm(allocations: allocations)
        }

        if self.contaminationSandbagged {
          self.eventEmitter.contaminate(allocations: allocations)
        }
        resolve.fulfill(allocations)
        do {
          try self.execution.executeWithAllocation(rawAllocations: allocations)
        } catch let err {
          let message = "There was an error executing with allocations. \(err.localizedDescription)"
          Log.logger.log(.error, message: message)
        }
      }
    }
  }