javascriptの勉強をしています。以下のコードで、xhrWrapperを、apiを取得後パースするといった再利用できるfunctionにしたいと思っています。
そこで、returnを使えばいいのかなと思い、14行目にreturn dataを入れたのですが、うまく戻ってくれません。
xhr.onload内のfunctionなので、returnが戻らないのはなんとなく理解できたのですが、実際どのようにして戻せばいいのかわからない状態です。
javascript
<!doctype html> <html> <head> <title>WebAPI</title> <script> var TOKEN = 'xxx'; var pathRepos = 'https://api.github.com/user/repos?visibility=private'; function xhrWrapper(path) { var xhr = new XMLHttpRequest(); xhr.open('get', path); xhr.setRequestHeader('Authorization', 'token ' + TOKEN); xhr.onload = function(){ var data = JSON.parse(xhr.response); return data; }; xhr.onerror = function () { console.log("error"); }; xhr.send(null); }; showBranch( xhrWrapper(pathRepos) ); function showBranch(d) { console.log(d); var l = d.length; for(var i = 0; i < l; i++){ var repoName = d[i].name; dataBranch = "https://api.github.com/user/repos/" + repoName + "/branches"; console.log(repoName); console.log(dataBranch); } } </script> </head> <body> </body> </html>
まだ回答がついていません
会員登録して回答してみよう