【发布时间】: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