2017-12-25 39 views
0

XMLHttpRequestの回答を他の関数(onreadystatechangefunctionではなく)に表示したい。xhr約束がエラーを返す

私は、例えば、コード

setInterval(function() { 
    let requestPromise = new Promise((resolve, reject) => { 
     var xhr = new XMLHttpRequest(); 
      xhr.open('POST', "location?act=update&id=<?php echo $id; ?>", true); 
      xhr.send(); 
      xhr.onreadystatechange = function(){ 
       if(this.readyState==4){ 
        if(this.status == 200){ 
         if(this.responseText){ 
          try{ 
           var data = JSON.parse(this.responseText); 
           if(data.command=="list"){ 
            var answerLat = parseFloat(data.lat); 
            var answerLng = parseFloat(data.lng); 
            var answerAccuracy = String(data.accuracy); 
            var answerTime = String(data.time); 
            resolve(answerLat); // Pump answerLat 
            resolve(answerLng); 
            resolve(answerAccuracy); 
            resolve(answerTime); 
           } 
           }catch(e){ 
          } 
         } 
        } 
       } 
      } 
    }); 
    requestPromise.then(googleMapsFunction); // googleMapsFunction will be called once the request is completed and will get answerLat as the argument 
}, 20000); 

を持っている:私は、他の関数でのGoogleマップを持っています。 xmlhttpreqestのデータ(answerLat、answerLng、answerAccuracy、answerTime)をマップ(function-googleMapsFunction)を使って他の関数にロードする方法はありますか?

が、私はそれを使用するときに、私は、エラーを参照してください。

Uncaught (in promise) ReferenceError: answerLat is not defined 

私は、それをパラメータとして受け入れることができますどのように?

答えて

1

私は問題を約束して解決すると思います。受信したデータを1つのオブジェクトに結合して、それに渡してみてくださいresolve()

setInterval(function() { 
    let requestPromise = new Promise((resolve, reject) => { 
     var xhr = new XMLHttpRequest(); 
     xhr.open('POST', "location?act=update&id=<?php echo $id; ?>", true); 
     xhr.send(); 
     xhr.onreadystatechange = function(){ 
      if(this.readyState==4 && this.status == 200 && this.responseText){ 
       try{ 
        var data = JSON.parse(this.responseText); 
        if(data.command=="list"){ 
         resolve({ 
          answerLat: parseFloat(data.lat), 
          answerLng: parseFloat(data.lng), 
          answerAccuracy: data.accuracy, 
          answerTime: data.time 
         }); 
        } 
       }catch(e){ 
        reject(e) 
       } 
      } 
     } 
    }); 
    requestPromise.then(googleMapsFunction); // googleMapsFunction will be called once the request is completed and will get answerLat as the argument 
}, 20000); 

const googleMapsFunction = (params) => { 
    const {answerLat, answerLng, answerAccuracy, answerTime} = params 
    // ... answerLat, answerLng, answerAccuracy, answerTime 
} 
+0

ありがとうございました!今すぐ私のコードをconstに貼り付ける必要があります。googleMapsFunction =(params)=> { const {answerLat、answerLng、answerAccuracy、answerTime} = params 私のGOOGLE MAPS FUNCTIONはありますか? } –

+0

おそらくはい、googleMapsFunctionを提供していただけますか? – tetta