【问题标题】:Promise chain works every time even though the return statement is conditional即使 return 语句是有条件的,Promise 链每次都有效
【发布时间】: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();
    });
}

我真的很困惑为什么会这样。我认为当没有返回承诺时,承诺链会中断?

【问题讨论】:

标签: javascript asynchronous promise


【解决方案1】:

如果你没有从 .then 返回 Promise,下一个 .then 将继续正常工作(因为没有引发错误),但其回调的参数将始终为 undefined:

Promise.resolve()
  .then(() => {
    // don't return anything
  })
  .then((param) => {
    console.log(param);
  });

如果您确定getNewShortListId,如果在解析时始终解析为不是undefined 的值,只需检查下一个.thenid 是否不是undefined

.then((id) => {
    if (id !== undefined) {
        listObj.__id = id;
        return new List(listObj).save();
    }
});

另一种选择是让上面的 .then 创建 Promise,而不是让下面的 .then

if (!listObj.unique)
  return Counters.getNewShortListId()
    .then((id) => {
      listObj.__id = id;
      return new List(listObj).save();
    })

如果您不喜欢嵌套的.thens 的外观,您可以将嵌套的.then 回调转换为您事先声明的命名函数(例如const processId = (id) =&gt; ...)。

你也可以抛出一个错误(例如if (listObj.unique) throw new Error())来完全跳出当前的.then链,控制流会立即转到下一个.catch,跳过中间的.thens——但错误一般不应用于控制流。

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 2019-05-14
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2019-09-28
    相关资源
    最近更新 更多