2017-03-08 38 views
2

我試圖在後端調用中實現異步,我一直在閱讀,似乎GParse是一個很好的庫來實現這一點,但它並不清楚我如何可以在一個正確的方式。誰能幫我?這是我的例子:GParse call BackendService async

def itemsResults 
    def locationResults 
    def itemsNearLocation 
    GParsPool.withPool { 
     itemsResults = {searchMyItems()}.async().call() 
     locationResults = {getLocations()}.async().call() 
     itemsNearLocation = {getItemsNear(locationResults)}.async().call() // i need locationresults answer in order to call this service 

    } 
    model.putAll(["items": itemsResults, 
        "itemsNearLocation":itemsNearLocation]) 

    return "myView" 

所以,我需要調用的API 2呼叫,然後在第三個我需要使用所謂的異步前的反應之一,並最終加入到我的模型。我怎樣才能做到這一點?

+1

可能是[數據流(HTTP一個很好的例子:// WWW。 gpars.org/1.0.0/guide/guide/dataflow.html) –

回答

3

你可以使用GPars數據流爲這個......像這樣的東西應該工作,我相信(沒有嘗試過,雖然):

import groovyx.gpars.dataflow.Dataflows 
import static groovyx.gpars.dataflow.Dataflow.task 

final def df = new Dataflows() 

task { 
    df.itemsResults = searchMyItems() 
} 

task { 
    df.locationResults = getLocations() 
} 

task { 
    df.itemsNearLocation = getItemsNear(df.locationResults) 
} 

def lastTask = task { 
    model.putAll(["items": df.itemsResults, 
        "itemsNearLocation":df.itemsNearLocation]) 
} 

lastTask.join() 
+0

你可以使用'final'作爲var的名字嗎? :) – injecteer

+0

@injecteer,很好的捕捉。它是一個保留關鍵字。可能是快速回復。但它是展示OP如何實現的。 – Rao

+0

@injecteer hehehe,fixed ;-) –