Начнем с простой перспективы: «chainPromises» возвращает обещание, поэтому вы можете смотреть на него следующим образом:
// Do all internal promises
var cp = chainPromises();
// After everything is finished you execute the final "then".
cp.then(function(val) {
console.log(val);
});
Вообще говоря, при возвращении обещания из предложения «then» , «тогда» функция инкапсулирующего обещания будет отмечена как завершенная только после того, как будет завершено внутреннее «затем».
Итак, если «a» является обещанием, а «b» является обещанием:
// "a"'s "then" function will only be marked as finished after "b"'s "then" function has finished.
var c = a.then(function () {
return b.then(function () {
console.log("B!");
};
};
// c is a promise, since "then" always returns a promise.
c.then(function() {
console.log("Done!");
};
Таким образом, выход будет:
B!
Done!
Обратите внимание, что если вы не «вернете» внутреннее обещание, это будет не так:
// "a"'s "then" function will only be marked as finished without waiting for "b"'s "then" to finish.
var c = a.then(function () {
// Notice we're just calling b.then, and don't "return" it.
b.then(function () {
console.log("B!");
};
};
// c is a promise, since "then" always returns a promise.
c.then(function() {
console.log("Done!");
};
Здесь мы не можем знать, что будет выводиться первым. Это может быть либо «B!» или «Готово!».