2016-02-01 45 views
2

我試圖實施以下方案: 1.客戶端調用流星方法。 2.在meteor-method內部,我將HTTP-Post發送到不同的服務器。 3.當響應HTTP-Call時,meteor方法應該返回true,如果發生錯誤,它應該返回false。流星包裝同步

這裏是我的流星方法是這樣的:

uploadUserImage: function(data_url,userid) { 
    asyncfnc =function(data,uid){ 
     HTTP.post("http://localhost:2000/upload", { 
      data: { 
       "data_url": data, 
       "user_id": uid 
      } 
     },function(err,res){ 
      console.log(res); 
      if (err){ 
       console.log("error"); 
       throw new Error(err.message); 
      } 
      else{ 
       console.log("return true"); 
       return true; 
      } 
     }); 
    }; 
    var waitForResult = Meteor.wrapAsync(asyncfnc); 
    var result = waitForResult(data_url,userid); 
    return result; 
} 

的HTTP呼叫的作品,我也進入HTTP.post功能的回調。 但是在我稱之爲流星法的客戶端,我沒有進入我的回調函數。它看起來像這樣:

Meteor.call("uploadUserImage",data_url,Session.get("newUserID"),function (err, res) { 
     if(err){ 
      console.log(err); 
     } else { 
      console.log('response: ', res); 
     } 
}); 

我在做什麼錯?爲什麼我的流星法不會返回任何東西? 一切正確與我的Meteor.wrapAsync()?

感謝您的幫助!

+1

你有錯誤嗎? – greedsin

回答

2

我找到了一個不需要Meteor.wrapAsync()的解決方案。

var url = "http://localhost:2000/upload"; 
    //synchronous GET 
    var result = Meteor.http.post(url,{ 
       data: { 
        "title": "i want to upload a picture", 
        "data_url": data_url, 
        "user_id": userid 
       },timeout:30000}); 
    if(result.statusCode==200) { 
     console.log(result); 
     console.log("response received."); 
     return result; 
    } else { 
     console.log("Response issue: ", result.statusCode); 
     var errorJson = JSON.parse(result.content); 
     throw new Meteor.Error(result.statusCode, errorJson.error); 
    } 

這使HTTP-Post-Call同步,所以不需要換行異步。

+2

你的答案仍然是異步...不保證只與超時同步..如果你的方法有多個用戶多次呼叫...你的超時將無用.. –

+0

你認爲this.unblock()可以做到這一點? – ant45de

+1

你需要'Meteor.wrapAsync()'...'this.unblock()'只會阻止你的方法阻止其他方法或訂閱當你的方法被調用...這與同步調用沒有任何關係.. –

0

你在這種情況下要求太多。 流星方法可以同步調用,但不建議如果方法是這樣做的遠程調用。

我的感覺是,你掛在一個程序編程模型,你想要一個同步結果1)調用你的服務器,2)發送到另一個遠程服務器的請求。你想從你的通話中獲得回報價值。它不這樣工作。

流星在很大程度上可以保護您免受異步性的影響,但有時您必須接受需要更多的工作才能正確處理它。

所以我的建議是使用回調通知。