【发布时间】:2019-12-17 21:05:57
【问题描述】:
我最近重组(扁平化)了这条链。然而,我很困惑为什么这个链在任何情况下仍然有效,即使.then 链接之一中的return 语句是有条件的:
function addList(name) {
let listObj = {};
listObj.name = name;
return nameExists(name) //returns a promise<boolean>
.then((result) => {
console.log("foo");
return result; //without this return statement the chain would break,
//which makes sense to me because it does not return a
//promise otherwise.
})
.then(bool => {
listObj.unique = !bool;
if (validListID(name)) { //this is a synchronous regex function
listObj.unique = false;
}
if (!listObj.unique)
return Counters.getNewShortListId(); // returns Promise
//Does not return promise when condition not met.
//However the next chain gets called in any case.
})
.then((id) => { //this gets called even when listObj.unique = true,
//also this works perfectly, why?
listObj.__id = id;
return new List(listObj).save();
});
}
我真的很困惑为什么会这样。我认为当没有返回承诺时,承诺链会中断?
【问题讨论】:
-
Promise.prototype.then-> Return value: "... - 不返回任何内容,then返回的承诺会以undefined值解决;... " -
JavaScript 函数一般:如果您没有显式返回值,它们会返回 undefined。
标签: javascript asynchronous promise