Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active June 15, 2017 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dogrunjp/0d787183f2e7b4456a9799d76068471c to your computer and use it in GitHub Desktop.
Save dogrunjp/0d787183f2e7b4456a9799d76068471c to your computer and use it in GitHub Desktop.
javascriptで非同期処理の完了を待って、フィルターした返り値をreturnする関数を書く方法

javascriptでd3-requestのような非同期処理の完了を待って、フィルターした返り値をreturnするfunctionを書く方法

インタラクションで取得した値を引数にAPIから何か結果を得て処理を進める想定のスクリプトです。

まず、リソースを呼び出し、返った値でUIを操作する関数がこんな感じだとすると、、、、

function show_friend_map(d){
    get_friend(d).then(function(r){
        //何かの操作
        console.log(r);
    })
}

そして、APIを叩いて(d3-requestである必要は全く無いのですが)返ってきた値をフィルターしreturn する関数です。 この例の場合さらに返ってきた値でAPIを叩いて、その返り値も最終的なパラメータに含めています。


function get_friend(g) {
    return new Promise(function(resolve){
        var target = 'http://friend.api/'+ g['_id'];
        d3.queue()
            .defer(d3.text, './phone_number.txt')
            .defer(d3.json, target_dst)
            .await(function(error, g, d){
                var dst = d['dist'];
                xh.domain(g).range([...Array(g.length).keys()]); 
                glst = g.split(','); 
                co.domain([d3.min(dst), d3.max(dst)]);
                var index_max = dst.indexOf(Math.max.apply(null, dst));
                var f_max = glst[index_max]; 
                get_family_info(f_max).then(function(d){ resolve([g, dst, d]) });
        })
    })
}


function get_family_info(i) {
    return new Promise(function(resolve){
        d3.json(`http://group.api/${i}`, function(r){
            resolve(r['Name']);
        })
    });
}

callbackと入れ子が過ぎてちょっと気持ち悪いのだけど、大きなデータを探索的に見せる場合、 全てのデータを最初に取得するのではなく、個別に選択的に取得する必要があり、現状はこういう風にしか書き方を思いつかない という感じです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment