Promise.all的限额是多少?

时间:2019-04-18 21:08:08

标签: node.js es6-promise

最近,我在解决大量承诺时遇到了以下错误:

  

RangeError:传递给Promise.all的元素过多

我找不到有关MDN或ECMA-262限制的任何信息。

3 个答案:

答案 0 :(得分:6)

根据源代码对象V8/V8Promise错误代码TooManyElementsInPromiseAll

  T(TooManyElementsInPromiseAll, "Too many elements passed to Promise.all")

有此限制。对于Promise.all,即C ++ PromiseAll,我们有一个MaximumFunctionContextSlotskPromiseAllResolveElementCapabilitySlot的概念,here是源代码中最有趣的东西:

// TODO(bmeurer): Move this to a proper context map in contexts.h?
  // Similar to the AwaitContext that we introduced for await closures.
  enum PromiseAllResolveElementContextSlots {
    // Remaining elements count
    kPromiseAllResolveElementRemainingSlot = Context::MIN_CONTEXT_SLOTS,

    // Promise capability from Promise.all
    kPromiseAllResolveElementCapabilitySlot,

    // Values array from Promise.all
    kPromiseAllResolveElementValuesArraySlot,

    kPromiseAllResolveElementLength
  };

我希望会看到类似here

的错误提示
ThrowTypeError(context, MessageTemplate::TooManyElementsInPromiseAll);

Here是引发TooManyElementsInPromiseAll错误的代码。感谢克拉伦斯,这为我指明了正确的方向!

BIND(&too_many_elements);
  {
    // If there are too many elements (currently more than 2**21-1), raise a
    // RangeError here (which is caught directly and turned into a rejection)
    // of the resulting promise. We could gracefully handle this case as well
    // and support more than this number of elements by going to a separate
    // function and pass the larger indices via a separate context, but it
    // doesn't seem likely that we need this, and it's unclear how the rest
    // of the system deals with 2**21 live Promises anyways.
    Node* const result =
        CallRuntime(Runtime::kThrowRangeError, native_context,
                    SmiConstant(MessageTemplate::kTooManyElementsInPromiseAll));
    GotoIfException(result, &close_iterator, var_exception);
    Unreachable();
  }

此限制为here

// Check if we reached the limit.
    TNode<Smi> const index = var_index.value();
    GotoIf(SmiEqual(index, SmiConstant(PropertyArray::HashField::kMax)),
           &too_many_elements);

所以kMax应该解决这个线索!

答案 1 :(得分:2)

我可以说什么限制似乎是什么,尽管我无法确切地指出为什么正是它在V8源代码中的用法。我编写了以下代码(如果无聊,请运行它,这需要一段时间):

if (!window.chrome) {
  throw new Error('Only try this in Chromium');
}

// somewhere between 1e6 and 1e7
let testAmountStart = 5.5e6;
let changeBy = 4.5e6;
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const next = (testAmount) => {
  changeBy = Math.ceil(changeBy / 2);
  if (changeBy === 1) {
    console.log('done');
    return;
  }
  console.log('start ' + testAmount);
  const proms = new Array(testAmount).fill(undefined);
  Promise.all(proms)
    .then(() => {
      // make this loop not fully blocking
      // give time for garbage collection
      console.log(testAmount + ': OK');
      delay(100).then(() => next(testAmount + changeBy));
    }).catch((e) => {
      console.log(testAmount + ': ' + e.message);
      delay(100).then(() => next(testAmount - changeBy));
    });
};
next(testAmountStart);

结果:传递带有2097151个元素的数组时引发错误,但2097150个元素可以:

const tryProms = length => {
  const proms = new Array(length).fill(undefined);
  Promise.all(proms)
      .then(() => {
      console.log('ok ' + length);
    }).catch(() => {
      console.log('error ' + length);
    });
};
tryProms(2097150);
tryProms(2097151);

因此,限制为2097150。可能与2097151为0x1FFFFF有关。

答案 2 :(得分:2)

V8 unit tests中,我们看到了:

// Make sure we properly throw a RangeError when overflowing the maximum
// number of elements for Promise.all, which is capped at 2^21 bits right
// now, since we store the indices as identity hash on the resolve element
// closures.
const a = new Array(2 ** 21 - 1);
const p = Promise.resolve(1);
for (let i = 0; i < a.length; ++i) a[i] = p;
testAsync(assert => {
  assert.plan(1);
  Promise.all(a).then(assert.unreachable, reason => {
    assert.equals(true, reason instanceof RangeError);
  });
});

看起来元素的最大数量上限为2 ^ 21(= 2097151),这符合其他答案进行的实际测试。