2017-06-15 7 views
0

League of Legends APIで練習コーディングをしたい。これを行うには、まずパッチバージョン(例: "7.12.1")とチャンピオンデータ(JSON)の2つの情報が必要です。ネスティングの約束が働いていない(jquery + League of Legends API)

私が抱えている問題は、GetData()がネストされた約束でも、GetPatch()が解決するのを待っていないということです。

var URL = "https://ddragon.leagueoflegends.com/" 
 
    var patch, data 
 

 
    var GetPatch = new Promise(function(resolve) { 
 
    $.getJSON(URL + "api/versions.json", f = x => { 
 
     patch = x[0] 
 
     console.log("patch version: " + patch) 
 
     resolve() 
 
    }) 
 
    }) 
 

 
    var GetData = new Promise(function(resolve) { 
 
    $.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json", g = x => { 
 
     data = x.data 
 
     console.log(data) 
 
     resolve() 
 
    }) 
 
    }) 
 

 
    GetPatch.then(function() { 
 
    GetData.then(function() { 
 
     RunApp() 
 
    }) 
 
    }) 
 

 
    function RunApp() { 
 
    console.log("everything is working") 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

+1

あなたは '$ .getJSON'などのようなjQueryのAJAX機能がすでに約束を返すことを知っていたが - 'f ='と 'g =' ...を削除するだけです。 'x =>' –

+1

を使用して、約束を作成する方法はgetJSONを "並列"で実行することを意味します –

+0

矢印機能に関するJaromanda 。 '$ .getJSON'関数を正しく設定するにはどうしたらいいですか? あなたに私にどのように表示することができれば、最高の答えをお伝えしたいと思います。 – zack

答えて

2

まず、$アヤックスのようなjQueryのAJAX機能は、すでに約束第二

、あなたが約束を設定する方法を返す、あなたはすぐに$ .getJSONを実行している

あなたのコードは次のようなものになる可能性があります。var patch, data

var URL = "https://ddragon.leagueoflegends.com/" 

var GetPatch = function() { 
    return $.getJSON(URL + "api/versions.json").then(x => x[0]); 
}) 

var GetData = function (patch) { 
    return $.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json").then(x => ({patch: patch, data: x.data})); 
}) 

GetPatch() 
.then(GetData) 
.then(RunApp); 

function RunApp({patch, data}) { 
    // here you can access patch and data if you need to 
    console.log("everything is working") 
} 

あなただけdata別の選択肢

return $.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json").then(x => x.data); 
... 
function RunApp(data) { 
    // here you can access data 
    console.log("everything is working") 
} 

RunAppに必要がある場合 - おそらく "すっきり"

var URL = "https://ddragon.leagueoflegends.com/" 

var GetPatch = function() { 
    return $.getJSON(URL + "api/versions.json"); 
}) 

var GetData = function (patch) { 
    // note the patch[0] below 
    return $.getJSON(URL + "cdn/" + patch[0] + "/data/en_US/champion.json"); 
}) 

GetPatch() 
.then(GetData) 
.then(RunApp); 

function RunApp(result) { 
    // result.data is what x.data was in your code 
    console.log("everything is working") 
} 
+0

シンプルで効果的なソリューションをありがとう! – zack

関連する問題