2017-03-26 5 views
0

Ich habe eine Kette von Promise wie unten Code. Ich möchte die dritte Promise warten auf den Abschluss der zweiten, aber es ist nicht! Kann jemand das Problem erklären?Verkettung

var condition = true; 
 

 
// Promise 
 
var willIGetNewPhone = new Promise(
 
    function (resolve, reject) { 
 
     if (condition) { 
 
      var phone = { 
 
       brand: 'Samsung', 
 
       color: 'black' 
 
      }; 
 
      setTimeout(function(){ 
 
       console.log("First Prommis!");       
 
       resolve(phone); 
 
      }, 2000) 
 
     } else { 
 
      var reason = new Error('Has not condition!'); 
 
      reject(reason); 
 
     } 
 

 
    } 
 
); 
 

 
var showOff = function (phone) { 
 
    var message = 'Need New Phone ' + 
 
       phone.color + ' ' + phone.brand + ' phone'; 
 
    setTimeout(function(){ 
 
     console.log("Second promis!"); 
 
     return Promise.resolve(message); 
 
    }, 1000) 
 
}; 
 

 
willIGetNewPhone 
 
.then(showOff) 
 
.then(function (fulfilled) { 
 
    console.log("Third Pramis!");  
 
}) 
 
.catch(function (error) { 
 
    console.log(error.message); 
 
});

Antwort

1

Ihr Problem ist, dass Sie von der showOff Funktion ein Versprechen nicht zurück. Eigentlich gibst du nichts zurück.

Der Code return Promise.resolve(message); die anonyme Funktion liefert Ihnen für setTimeout erstellt, nicht die showOff -function.

Also muss man ein Versprechen wie diese zurückgeben:

var showOff = function (phone) { 
    var message = 'Need New Phone ' + 
       phone.color + ' ' + phone.brand + ' phone'; 
    return new Promise(function(resolve) { 
     setTimeout(function() { 
      resolve(message); 
     }, 1000); 
    }); 
}; 

Sie sehen also, im Grunde Ihre Debugging-Timeout Ihr Problem.