2016-08-08 6 views
-1

値は置き換えられず、関数は0を返します。 (反応ネイティブ0.30、IOS 10.0シミュレータ)関数からXMLHttpRequestレスポンスを返す方法は?

export function getCategoryList() { 
 
    var xhr = new XMLHttpRequest(); 
 
    jsonResponse = null; 
 

 
    xhr.onreadystatechange = (e) => { 
 
    if (xhr.readyState !== 4) { 
 
     return; 
 
    } 
 

 
    if (xhr.status === 200) { 
 
     console.log('SUCCESS', xhr.responseText); 
 
     jsonResponse = JSON.parse(xhr.responseText); 
 
    } else { 
 
     console.warn('request_error'); 
 
    } 
 
    }; 
 

 
    xhr.open('GET', 'https://httpbin.org/user-agent'); 
 
    xhr.send(); 
 

 
    return jsonResponse; 
 
}

+0

リクエストは、リクエストが送信され、あなたの関数はNULL値を返し、その後、いくつかの時間後にリクエストが完了したことを意味し、非同期です。コールバック関数を 'getCategoryList()'(簡単)または約束(少し難しいが、それほど多くない)に渡すことに注目してください。 – Archer

+5

Read:http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Cherniv

+0

[promise](https://developer.mozilla)を検索してください。 .org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) –

答えて

1

あなたがそのような値を返すことはできません。

私は、コールバックや約束のどちらかと一緒に行くことをお勧め:

コールバック:

function getCategoryList(callback) { 
 
    var xhr = new XMLHttpRequest(); 
 

 
    xhr.onreadystatechange = (e) => { 
 
    if (xhr.readyState !== 4) { 
 
     return; 
 
    } 
 

 
    if (xhr.status === 200) { 
 
     console.log('SUCCESS', xhr.responseText); 
 
     callback(JSON.parse(xhr.responseText)); 
 
    } else { 
 
     console.warn('request_error'); 
 
    } 
 
    }; 
 

 
    xhr.open('GET', 'https://httpbin.org/user-agent'); 
 
    xhr.send(); 
 
} 
 

 
getCategoryList(data => console.log("The data is:", data));

約束:

function getCategoryList() { 
 
    var xhr = new XMLHttpRequest(); 
 

 
    return new Promise((resolve, reject) => { 
 

 
    xhr.onreadystatechange = (e) => { 
 
     if (xhr.readyState !== 4) { 
 
     return; 
 
     } 
 

 
     if (xhr.status === 200) { 
 
     console.log('SUCCESS', xhr.responseText); 
 
     resolve(JSON.parse(xhr.responseText)); 
 
     } else { 
 
     console.warn('request_error'); 
 
     } 
 
    }; 
 

 
    xhr.open('GET', 'https://httpbin.org/user-agent'); 
 
    xhr.send(); 
 
    }); 
 
} 
 

 
getCategoryList().then(res => console.log("The result is", res));

0

XHRが同期(xhr.open('GET', 'https://httpbin.org/user-agent', false))の場合、要求の応答が返され、要求が完了すると破損する無限ループが発生します。

  • 同期XHRは推奨されています。
  • XHRが終了していない間(例:ゲーム)、無限ループがページを停止します。

function getCategoryList() { 

    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", "https://httpbin.org/user-agent", false); 
    xhr.send(); 

    // stop the engine while xhr isn't done 
    for(; xhr.readyState !== 4;) 

    if (xhr.status === 200) { 

     console.log('SUCCESS', xhr.responseText); 

    } else console.warn('request_error'); 

    return JSON.parse(xhr.responseText); 
} 
+1

同期HTTPリクエストはサポートされていません。 – iwasmusic

+0

@wasmusicこれらは廃止されましたが、今後削除される予定です。それがあなたが望んだことです(「どうすればXMLHttpRequestレスポンスを返すことができますか...」)。 – Hydro

関連する問題