2017-05-18 20 views
1

我打電話的web服務陣營本土:如何獲得API調用的回調另一類

這裏是我的代碼:

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

您需要使用Promises。

更改callPostApi函數返回一個承諾,那麼你就可以額外鏈thencatchfinally電話。

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

謝謝,它工作正常。 –