summaryrefslogtreecommitdiffstats
path: root/js/src/tests/test262/language/expressions/await/for-await-of-interleaved.js
blob: 39bcda612edca544198627f46d07e2210dfba87a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// |reftest| async
// Copyright 2018 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
author: Maya Lekova <mslekova@chromium.org>
esid: await
description: >
  for-await-of iteration and builtin Promises are properly interleaved,
  meaning await in for-of loop takes only 1 tick on the microtask queue.
flags: [async]
features: [async-functions, async-iteration, generators]
includes: [compareArray.js]
---*/

const actual = [];
const expected = [
  'Promise: 6',
  'Promise: 5',
  'Await: 3',
  'Promise: 4',
  'Promise: 3',
  'Await: 2',
  'Promise: 2',
  'Promise: 1',
  'Await: 1',
  'Promise: 0'
];
const iterations = 3;

async function* naturalNumbers(start) {
  let current = start;
  while (current > 0) {
    yield Promise.resolve(current--);
  }
}

async function trigger() {
  for await (const num of naturalNumbers(iterations)) {
    actual.push('Await: ' + num);
  }
}

async function checkAssertions() {
  assert.compareArray(actual, expected,
    'Async/await and promises should be interleaved');
}

function countdown(counter) {
  actual.push('Promise: ' + counter);
  if (counter > 0) {
    return Promise.resolve(counter - 1).then(countdown);
  } else {
    checkAssertions().then($DONE, $DONE);
  }
}

trigger();
countdown(iterations * 2);