2017-05-18 8 views
1

をAPI呼び出しのコールバックを取得するために、どのように私はここでリアクト - ネイティブ:別のクラスに

Webサービスを呼び出していますことは、私のコードです:

var result; 
export function callPostApi(urlStr, params) 
{ 
     fetch(urlStr, {method: "POST", headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
      }, 
      body: JSON.stringify(params)}) 
      .then((response) => response.json()) 
      .then((responseData) => { 
       result = JSON.stringify(responseData) 
      }) 
      .catch((error) => { console.error(error); 

      Alert.alert('Alert Title failure' + JSON.stringify(error)) 
      }) 
      .done(); 
      return result 
} 

私はここからかけています:

callapi(){ 
    var dict = { 
      email: '[email protected]', 
      password: '123456', 
     } 
    result = callPostApi('http://demo.com', dict) 
} 

現在、非同期モードで呼び出していますが、このメソッドの下にコードが書き込まれています。上記のメソッドの呼び出し直後にコードが実行されます。

上記のメソッドの下に書かれたコードを実行できるように、サーバからの結果が受信されたときにコールバックが必要です。サーバからの応答を受け取った後に実行されます。

答えて

1

約束を使用する必要があります。

約束、その後することができますチェーンの追加 thencatchfinally呼び出しを返すために、あなたの callPostApi機能を変更

export function callPostApi(urlStr, params) { 
    return fetch(urlStr, { 
      method: "POST", 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json', 
      }, 
      body: JSON.stringify(params) 
     }) 
     .then((response) => response.json()) 
     .then((responseData) => { 
      result = JSON.stringify(responseData) 
     }) 
     .catch((error) => { 
      console.error(error); 
      Alert.alert('Alert Title failure' + JSON.stringify(error)) 
     }); 
} 


callapi() { 
    callPostApi('http://demo.com', { 
      email: '[email protected]', 
      password: '123456', 
     }) 
     .then((response) => { 
      // Continue your code here... 
     }); 
} 
+0

ありがとうございました。 –

関連する問題