繁体   English   中英

为什么总是用 undefined 调用?

[英]Why then is always called with undefined?

我有以下承诺链:

return new Promise((resolve, reject) => {
  isUserExists(user.username, user.email).then((existResult) => {
    /// already exists
    if (existResult.rows[0].exists == true) {
      reject('Already exists');
    } else {
      return insertCity({
        city_id: user.city_id,
        city_name: user.city_name
      });
    }
  }).then((cityResult) => {
    /// this is one is always called even I didn't called insertCity above
    console.log(cityResult); /// could be undefined if not called
    return insertUser(user); /// I don't want this to be executed
  });
});

如果用户已经存在,我调用reject('Already exists') 但无论如何, next then无论如何insertUser被调用,这意味着insertUser也被调用。 我不希望它发生。 我只想在任何时候调用reject时停止一切。 返回拒绝( Already exists )没有帮助。 我该如何解决问题? 看来我不明白 Promises 的核心内容。

您的代码中有几个问题:

  • 您不需要将isUserExists(user.username, user.email)包装在Promise构造函数中,因为它已经返回了Promise

  • 在第一个.then()方法的回调函数中,调用reject()拒绝新创建的Promise但它不会停止第一个.then()方法的回调函数的执行,直到它隐式返回undefined ,然后导致调用第二个.then()块。

解决方案

您不需要Promise构造函数。 一旦确定用户已经存在,就可以抛出错误。

return isUserExists(user.username, user.email)
   .then((existResult) => {
       /// already exists
       if (existResult.rows[0].exists == true) {
         throw new Error("already exists");
       }
       
       return insertCity({ city_id: user.city_id, city_name: user.city_name });
   })
   .then((cityResult) => {
       console.log(cityResult);
       return insertUser(user);
   });

确保在调用代码中添加.catch()块以在用户已存在时处理错误。

你有两个独立的承诺。

如果existResult.rows[0].exists == true那么你拒绝外部承诺。

这不会影响尚未被拒绝的内部承诺。 所以它then继续。


不要嵌套承诺。

如果您想从承诺链内部触发拒绝链,则抛出异常。

 function isUserExists() { return Promise.resolve("OK") } function getPromise() { return isUserExists().then(function() { // it exists! if (true) { throw "User exists."; } }).then(function() { console.log("This won't be called"); }); } getPromise().then(function() { console.log("Also won't be called"); }).catch(function() { console.log("Error here!"); });


尽管如此,这仍然相当混乱。 你最好使用awaitasync语法:

async function example() {
    const existResult = await isUserExists(user.username, user.email);
    if (existResult.rows[0].exists == true) throw "Already exists";
    const cityResult = await insertCity({
        city_id: user.city_id,
        city_name: user.city_name
    });
    console.log(cityResult);
    return insertUser(user);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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