2016-08-30 1 views
1

ich mache etwas falsch, sehr neu auf Knoten js so mit mir bitte entblössen.NodeJS versprechen falsche Verwendung

Environment: node V5.1.0 auf Windows7.

Ich versuche, Daten zu publish_url mit Post zu senden. Ich möchte eine weitere Funktion in den Fang der init oder der then ausführen. Aber erreichen Sie diese Teile nicht.

Die Drucke „Aufruf zum Erfolg Handle func“ und „Anruf fehlgeschlagen Handle func“ wird nicht aufgerufen werden.

Bitte geben Sie mir, was ich falsch mache?

var request = require('request'); 
var publish_url = "https://some_server.com"; 
function publish_data(url, data) { 
    return new Promise(function (resolve, reject){ 
     request.post(
      url, 
      { json: 
       {"handshake":{"data":data}} 
      }, 
      function (error, response, body) { 
       if (!error && response.statusCode == 200) { 
        console.log(body); 
        resolve(body); 
       } else { 
        console.log("Error:",body); 
        reject(body); 
       } 
      } 
     ); 
    }); 
} 

function init(){ 
    console.log("init 1"); 
    try{ 
     publish_data(publish_url, 5).then(
      function(obj){ 
       console.log("call to success handle func"); 
      }); 

    }catch(e){ 
     console.log("call to failed handle func");  
    } 

    console.log("init 3"); 
} 

console.log("start"); 
init(); 
console.log("end"); 
+0

Hey, "nacktes" WAS mit dir? Vielleicht meintest du "Bär mit mir" ??? –

Antwort

3

Verwenden Sie keine try-catch

Versprechungen, die Art und Weise funktioniert:

publish_data(publish_url, 5).then(function(obj){ 
console.log("call to success handle func"); 
}).catch(function(data){ 
console.error(data); 
}); 

Hier ist ein einfaches Beispiel für JS Versprechen:

function firstFunct(){ 
 
return new Promise(function(resolve,reject){ 
 
    data = 5; 
 
    if(data == 5) resolve(data); 
 
    else reject(data); 
 
}) 
 
} 
 

 
firstFunct().then(function(data){ 
 
    console.log("Resolved, data expected to be 5:" + data); // if Promise is resolved 
 
}).catch(function(data){ 
 
    console.error("Rejected, data is not 5:" + data) // if Promise is rejected 
 
});

Verwandte Themen