执行异步函数列表

时间:2021-05-25 11:57:16

标签: javascript

我有一个练习来制作一个函数 executeFunctions,它将异步函数列表和一个参数作为参数,例如数字。 这些函数必须一个接一个地发生,所以如果 fun1 结束,fun2 需要从 fun1 返回的值开始。 问题是我不能使用 asyncawait。我想使用 reduce 来完成它,但我猜它想执行 const res1 并在返回值之前更进一步(因为 setTimeout)。 没有 asyncawait 有什么办法吗?

const fun1 = function(value) {
   
    return setTimeout(() => value*2, 3000)
}
const fun2 = function(value) {
    
    return setTimeout(() => value*4, 3000)
}
const cb2 = (value) => {
   return value*10

}

const executeFunctions = (funTab, cb) => (n) => {
    const res1= funTab[0](n)
    console.log(res1)
    const resReduce = funTab.reduce((prev,curr) => {
        const res2 = curr(prev)
        return prev+res2
    }, res1)
    return cb(resReduce)

};
executeFunctions([fun1,fun2], cb2)(2)

1 个答案:

答案 0 :(得分:1)

我们可以使用 Promise 链:

library(tidyverse)
df <- data.frame(Region = c("Asia","Asia","Africa","Europe","Europe"),
                 Emp = c(120,40,10,67,110),
                 Sales18 = c(12310, 4510, 1140, 5310, 16435),
                 Sales19 = c(15670, 6730, 1605, 6120, 1755))


df %>%
  group_by(Region) %>%
  summarise(across(
    .cols = starts_with("Sales"),
    .fns = list(w_mean = ~ weighted.mean(.x, w = Emp), mean = ~ mean(.x)), 
    .names = "{.col}_{.fn}")
  )
#> # A tibble: 3 x 5
#>   Region Sales18_w_mean Sales18_mean Sales19_w_mean Sales19_mean
#>   <chr>           <dbl>        <dbl>          <dbl>        <dbl>
#> 1 Africa          1140         1140           1605         1605 
#> 2 Asia           10360         8410          13435        11200 
#> 3 Europe         12224.       10872.          3407.        3938.

或者,我们也可以使用建议的 reduce 解决方案的修改版本,通过如下更改 const fun1 = function(value) { return Promise.resolve(value * 2); } const fun2 = function(value) { return Promise.resolve(value * 2); } const fun3 = function(value) { return Promise.resolve(value * 2); } const executeFunctions = (funcList) => (n) => { let chain = Promise.resolve(n); // initial value for (let i = 0; i < funcList.length; i++) { chain = chain.then(funcList[i]); // keep chaining } return chain; // last promise }; const main = () => { // we need to wait for the last promise in order to print the result executeFunctions([fun1, fun2, fun3])(2).then(x => console.log('solution is:', x)); } main() // prints: "solution is: 16" 的实现(其余代码应保持在前面的代码段中):

executeFunctions
相关问题