2016-05-08 21 views
0

EDITメソッドデータを呼び出すとまだ設定されていない非同期呼び出しであると思います。JSNI関数から返されるGWT JSNI関数

String theData = getData("trainer") // not set yet 

私は以下のJSNI機能を持っています。この関数を呼び出すと、空の文字列が返されますが、console.logの前にデータがあることが示されます。何らかの理由でデータが返されないようです。

public native String getData(String trainerName)/*-{ 
    var self = this; 
    $wnd.$.get("http://testdastuff.dev/trainerstats", { trainer: trainerName}) 
    .fail(function() { 
     $wnd.console.log("error"); 
     }) 
    .done(function(data) { 
     console.log("DATA IS: " + data); 
     return data; 
    }); 

    }-*/; 

答えて

1

あなたは非同期呼び出しであると考えています。 doneに渡されたコールバックの戻り値は、元の呼び出しに戻されません。

次のコードを使用した場合は、コンソールに2つのメッセージが表示されます。最初は空のデータが、2番目のデータには正しいデータが表示されます。

String theData = getData("trainer"); 
consoleLog("The data is " + theData); 
// suppose consoleLog as a native function to console.log 

このように、あなたはおそらくコールバックを行うべきです。

.done(function(data) { 
    console.log("DATA IS: " + data); 
    theData = data; // if theData is within the same scope and you want to store 
    doSomethingWith(theData); // <-- here you can interact with theData 
}) 

doSomethingWith(theData)はJavaメソッドの呼び出しでもあります。

+0

ありがとうございました。良い解決策のようです。 – james

関連する問題