【问题标题】:Handling nested promises处理嵌套的 Promise
【发布时间】:2020-12-18 00:47:52
【问题描述】:

我试图拒绝嵌套承诺中的值,但它似乎并没有真正正确地拒绝它。在下面的代码中,当我从 promiseVariable 收到错误时,它不会因错误而拒绝。在 promiseVariable.catch 语句中,我有拒绝(错误)。那不应该拒绝整个承诺的那个错误吗?

return new Promise((resolve, reject) => {
  const user = anotherFunction();
  if (!user) {
     promiseVariable.then((data) => {
       user = data;
     }).catch((err) => {
       reject(err)
     })
 }
 resolve(user);
});

【问题讨论】:

    标签: node.js promise async-await


    【解决方案1】:

    因为它将启动promiseVariable 链并跳转到resolve。在.then,你应该在那里解决,或者放一个else

    return new Promise((resolve, reject) => {
      const user = anotherFunction();
      if (!user) {
        promiseVariable
        .then(resolve)
        .catch(reject);
      } else {
        resolve(user);
      }
    });
    

    【讨论】:

      【解决方案2】:

      如果这是一个词,您似乎过于乐观了。您只需 "await" 即可完成您的其他承诺。

      这里,anotherFunction 是一个模拟的 Promise,3 秒后它会为您的条件 if(!user) 返回一个有效对象。

      您可以尝试将 resolve({user: 1234}) 更改为 false(或 falsy)值以查看其拒绝。

      function anotherFunction() {
          return new Promise((resolve,reject) => {
              setTimeout(() => resolve({user: 1234}), 3000)
          });
      }
      
      async function mainFunction() {
          const user = await anotherFunction();
          return user || {error: 404};
      }
      
      mainFunction().then(result => console.log(result));

      【讨论】:

      • 我不能做 new Promise(async (resolve,reject) {... 因为我的 linter 不允许函数在 new Promise 中异步。
      • @siri,好吧,下次记得在你的问题中说明这些限制,这样我们才能完全理解你。
      • 直到我尝试了您的解决方案才知道这是一个约束。但是,还有其他方法可以按照您的建议进行吗?好像更干净了
      • 好吧,如果你能摆脱mainFunction(在我的例子中)里面的promise,它肯定会更干净。
      • @siri 我编辑了我的代码,我想这就是你要找的。如果有帮助,请告诉我。
      猜你喜欢
      • 2017-04-15
      • 2020-05-15
      • 1970-01-01
      • 2021-08-03
      • 2020-05-17
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多