【问题标题】:How to wrap a conditional statement in a Promise [duplicate]如何在 Promise 中包装条件语句 [重复]
【发布时间】:2019-05-28 10:54:57
【问题描述】:

我有一个条件if 语句,其逻辑需要包装在一个承诺中,因为if 之后的逻辑只能在它之后执行。

// WRAP 'if' statement below IN A PROMISE
if (a) { // could be true or false. If false, resolve the promise
    // logic here
}

.then(
    // execute logic after if here
)

我是 nodejs 的新手,正在尝试解决这个问题。我该如何解决这个问题?

【问题讨论】:

  • 拜托,你能重新整理你的问题以便于理解吗?
  • 如果你没有任何异步处理,你不需要promise。您想要在 其他语句(如if 块)之后执行的任何语句都应该紧跟在同一块中的这些语句之后。如果您确实有一些异步 API 调用,请在您的代码中显示。

标签: javascript node.js promise


【解决方案1】:

只需将其包装成一个新的 Promise:

new Promise((resolve, reject) => {
   if(a){
      reject("error");
   } else {
     resolve(yourData);
   }       
})
.then(data => {
 // Do stuff
})
.catch(err => {
  // You should catch here an error rejected above
})

【讨论】:

    【解决方案2】:

    这个问题有点不清楚。这是根据我理解的答案。一旦解决或拒绝,您将无法在 Promise 中运行代码。

    new Promise((res, rej) => {
    
        if (false) {
    
    
        }
        res();
        console.log('More code') // this will not run
    
    }).then(() => {
    
        console.log('This will run')
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-10
      • 2016-12-08
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2015-10-02
      • 1970-01-01
      相关资源
      最近更新 更多