简体   繁体   English

JS:将多回调函数重构为Promise

[英]JS: Refactor multi-callback function into promise

I was wondering if someone knows a good way to refactor the following function into a more promise-esque function: 我想知道是否有人知道将以下功能重构为更像诺言的功能的好方法:

function runProcess(processStarted, processFinished) {
   getProcessId(processStarted)
   doABunchOfAsyncLogic(processFinished)
}

It is invoked like this: 它的调用方式如下:

runPromise(function handleStart(){...}, function handleEnd(){...})

This is not a good use-case for promises, because by its nature you need two callbacks: One for starting, one for finishing. 这不是诺言的好用例,因为从本质上讲,您需要两个回调:一个用于启动,一个用于完成。 But promises are one-offs: Once settled, they can't be re-settled or similar. 但是,诺言是一次性的:一旦解决,就无法重新结算或类似。

You can do it, by returning an array of two promises, or an object with the individual promises for "start" and "finish": 可以通过返回两个promise的数组,或返回“ start”和“ finish”的单个promise的对象来实现:

function runProcess() {
    return {
        start: new Promise(...),
        finish: new Promise(...)
    };
}

...but it's not a natural promise use-case. ...但这不是自然的承诺用例。

I'd probably expect the process to start during the function call, and only its end to be promise-ified. 我可能希望该过程在函数调用期间开始 ,并且只有结束是可以保证的。

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

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