for-await-of-interleaved.js (1333B)
1 // |reftest| async 2 // Copyright 2018 the V8 project authors. All rights reserved. 3 // This code is governed by the BSD license found in the LICENSE file. 4 5 /*--- 6 author: Maya Lekova <mslekova@chromium.org> 7 esid: await 8 description: > 9 for-await-of iteration and builtin Promises are properly interleaved, 10 meaning await in for-of loop takes only 1 tick on the microtask queue. 11 flags: [async] 12 features: [async-functions, async-iteration, generators] 13 includes: [compareArray.js] 14 ---*/ 15 16 const actual = []; 17 const expected = [ 18 'Promise: 6', 19 'Promise: 5', 20 'Await: 3', 21 'Promise: 4', 22 'Promise: 3', 23 'Await: 2', 24 'Promise: 2', 25 'Promise: 1', 26 'Await: 1', 27 'Promise: 0' 28 ]; 29 const iterations = 3; 30 31 async function* naturalNumbers(start) { 32 let current = start; 33 while (current > 0) { 34 yield Promise.resolve(current--); 35 } 36 } 37 38 async function trigger() { 39 for await (const num of naturalNumbers(iterations)) { 40 actual.push('Await: ' + num); 41 } 42 } 43 44 async function checkAssertions() { 45 assert.compareArray(actual, expected, 46 'Async/await and promises should be interleaved'); 47 } 48 49 function countdown(counter) { 50 actual.push('Promise: ' + counter); 51 if (counter > 0) { 52 return Promise.resolve(counter - 1).then(countdown); 53 } else { 54 checkAssertions().then($DONE, $DONE); 55 } 56 } 57 58 trigger(); 59 countdown(iterations * 2);