【问题标题】:Run N Promises with parallel limitation运行 N 个具有并行限制的 Promise
【发布时间】:2019-03-04 10:31:14
【问题描述】:

所以,我正在尝试运行 N 个具有并行计数限制的 Promise。例如,我希望在我的程序运行时有 3 个等待回调的承诺。不多,但仍然可能是这样的情况,当 2 个 Promise 起作用时(例如 - N = 5, 3 个并行,所以在程序结束时只有 2 个 Promise,没关系)

没有yield sleep 1,此代码不起作用,它将启动 3 funcs add,记录 3 "#{name about to create}" 就可以了。只要您可以等待,程序就会一直保持这种状态。

但是使用yield sleep 1 可以正常工作。

为什么?

co = require 'co'
Promise = require "bluebird"

in_progress = 0
check_num = 0
checks_list = []

add = (name) ->
    console.log "#{name} about to create"
    in_progress++
    new Promise (resolve, reject) ->
        setTimeout () ->
            console.log "#{name} completed"
            in_progress--
            resolve(name)
        , 3000

sleep = (t) ->
    new Promise (resolve, reject) ->
        setTimeout ->
            resolve()
        , t

run = () -> co ->
    while check_num < 5
        console.log "in progress: #{in_progress}"
        if in_progress < 3
            checks_list.push add("n#{check_num++}")
        # yield sleep 1


run().then () ->
    console.log checks_list

    Promise.all checks_list
    .then () ->
        console.log checks_list

P.S.这个问题与this 重复,但它是俄语的。

【问题讨论】:

    标签: javascript promise coffeescript


    【解决方案1】:

    没有yielding,你只会有一个无限循环。 setTimeout 回调永远不会发生,promise 永远不会解决,你的循环计数器永远不会改变。使用yield sleep 1,每次迭代都会中断循环,允许其他事情发生,这最终会减少in_progress,并允许创建更多add promise,直到check_num 为5。

    请注意,由于您使用的是 Bluebird,因此您不需要任何这些,甚至不需要 co

    Promise = require "bluebird"
    
    add = Promise.coroutine (name) ->
        console.log "#{name} about to create"
        yield Promise.delay 3000
        console.log "#{name} completed"
    
    Promise.map ("n#{check_num}" for check_num in [0..5]),
                add,
                concurrency: 3
    .then ->
        console.log "all done"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2012-02-05
      • 2022-01-11
      • 2017-12-08
      • 2016-02-23
      • 2019-06-03
      • 2014-04-21
      相关资源
      最近更新 更多