简体   繁体   中英

Chain of promise

I have a chain of Promise like below code. I want the third Promise to wait for finishing the second one, but it dosn't! Can anyone explain the problem?

 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); }); 

Your problem is that you don't return a Promise from the showOff function. Actually your returning nothing.

The code return Promise.resolve(message); returns the anonymous function you created for setTimeout , not the showOff -function.

So you have to return a promise like this:

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

So you see, basically your debugging-timeout is your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM