2017-05-16 68 views
-1

你好我親愛的程序員同伴,我想做一個多個http請求使用承諾知道什麼時候http請求完成,我有這個代碼,但不起作用,我去這裏尋求幫助。我如何做一個異步任務的多個請求,要知道當我完成所有請求

這是我的代碼:

promisesMappingIp(){ 
    var promises = []; 
    for(var i = 1; i < 255; i++){ 
    promises.push(this.http.get(`http://192.168.1.`+i+`/hello`).map((res:Response) => { 
      try{ 
       return res.json(); 
      }catch(err){ 
       return {}; 
      } 
      })); 
    } 

    Promise.all(promises).then(function(){ 
    promises.forEach((x) =>{ 
     x.subscribe(data => { 

     }); 
    }); 
    }).catch((err) =>{ 
    console.error(err); 
    }); 
} 

而且在我的控制檯拋出我的錯誤:

錯誤對象{_body:錯誤,狀態:0,OK:假,狀態文本: 「」,標題:對象,輸入:3,url:null}

我使用Ionic 2進行學校項目,我真的需要你的幫助,我想映射所有返回給我的響應=「問候!」的ip。

謝謝。

回答

0

您可以使用Observable

import {Observable} from 'rxjs/Rx'; 

promisesMappingIp() { 
    var promises = []; 
    for (var i = 1; i < 255; i++) { 

     promises.push(this.http.get(`http://192.168.1.` + i + `/hello`)); 
    } 

    Observable.forkJoin(promises) 
     .subscribe((response) => { 
      console.log(response[0]); 
      console.log(response[1]); 
     }); 
} 
0

Promise.all()具有快速失敗發送多個HTTP請求。這意味着一旦第一次承諾失敗,它就會失敗。

你需要攔截失敗,不傳播它,像這樣的東西:

promises.push(this.http.get(`http://192.168.1.`+i+`/hello`).map((res:Response) => { 
      try{ 
       return res.json(); 
      }catch(err){ 
       return {}; 
      } 
      }).catch(err=> ({ error: err }))); 
1

我已經解決了使用XMLHttpRequest來我的問題,這是我的代碼,我希望這有助於同一人問題:

getService(ip: string, param: string): Promise<any> { 
    let url: string = `http://${ip}/${param}`; 
    return new Promise((r,j) =>{ 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", url, true); 
    xhr.onload = function(e){ 
     if (xhr.readyState === 4) { 
     r(ip); 
     } 
    } 
    xhr.onerror = function(err){ 
     r(null); 
    } 
    xhr.send(null); 
    }); 
} 

這是我使用的呼叫methor:

getIpList(){ 
    let promises = []; 
    for(var i = 1; i < 255; i++){ 
    promises.push(this.nodeProvider.getService(`192.168.1.${i}`, 'hello')); 
    } 
    Promise.all(promises).then((arrayIp) => { 
    let clean = arrayIp.filter(ip => !!ip); 
    }); 
} 

我希望我已經能夠解決您的問題