【问题标题】:How can I resolve or reject a promise based on a another promise?我如何解决或拒绝基于另一个承诺的承诺?
【发布时间】:2021-08-25 21:01:58
【问题描述】:
function process () {
 return new Promise((resolve, reject) => {


    //make sure module exists
    let module = modules[queueData.module];
    if (!module) reject('module not found: '+queueData.module);

    //make sure processor exists
    let processor = fileProcessors[module.type];
    if (!processor) reject('processor not found: '+module.type);

      return anotherPromiseFunction();
})
}

processFile().catch(e => console.error)

anotherPromiseFunction() 返回一个承诺。通常在 .then() 中我可以返回一个承诺,让 then() 等待该承诺完成,但是在创建承诺时我该怎么做呢?

我应该这样做吗:

    anotherPromiseFunction()
        .then(e=>resolve(e))
        .catch(e=>reject(e))

好像不对……

【问题讨论】:

  • 为什么“看起来不对”?您有没有按预期工作的具体示例?
  • 我猜只是因为我是手动获得结果,而不是仅仅向上转发整个承诺......但如果这是你应该这样做的,那么我猜它是好的
  • 我看不懂这段代码。在第一个 sn-p 中,Promise 包装器的意义何在?你已经有一个承诺,所以再次包装它没有任何好处。在第二个 sn-p 中,resolve 来自哪里?大概是另一个承诺包装器,但是我们又回到了第一个问题......为什么额外的包装器什么都不做?如您所说,只需在没有包装的情况下返回承诺即可。见What is the explicit promise construction antipattern and how do I avoid it?
  • @ggorlen 我想我把它简化了(我现在编辑了更多)。该函数期望返回一个 Promise,但在运行 anotherPromiseFunction() 之前它需要检查其他一些事情,这需要拒绝该 Promise。

标签: javascript function asynchronous promise


【解决方案1】:

您可能不需要new Promise。 “模块存在”和“处理器存在”这两种情况可以分开处理,之后直接调用anotherPromiseFunction即可:

//make sure module exists
let module = modules[queueData.module];
if (!module) {
  return Promise.reject(new Error('module not found: '+queueData.module));
}

//make sure processor exists
let processor = fileProcessors[module.type];
if (!processor) {
  return Promise.reject(new Error('processor not found: '+module.type));
}

return anotherPromiseFunction();

如果封闭函数是异步函数,则可以直接抛出错误:

async function run() {
  //make sure module exists
  let module = modules[queueData.module];
  if (!module) {
    throw new Error('module not found: '+queueData.module);
  }

  //make sure processor exists
  let processor = fileProcessors[module.type];
  if (!processor) {
    throw new Error('processor not found: '+module.type);
  }

  return anotherPromiseFunction();
}

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 2023-03-26
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多