async-await-basic.js 17.3 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
// Flags: --allow-natives-syntax
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// Do not install `AsyncFunction` constructor on global object

function assertThrowsAsync(run, errorType, message) {
  var actual;
  var hadValue = false;
  var hadError = false;
  var promise = run();

  if (typeof promise !== "object" || typeof promise.then !== "function") {
    throw new MjsUnitAssertionError(
        "Expected " + run.toString() +
        " to return a Promise, but it returned " + PrettyPrint(promise));
  }

  promise.then(function(value) { hadValue = true; actual = value; },
               function(error) { hadError = true; actual = error; });

  assertFalse(hadValue || hadError);

26
  %PerformMicrotaskCheckpoint();
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

  if (!hadError) {
    throw new MjsUnitAssertionError(
        "Expected " + run + "() to throw " + errorType.name +
        ", but did not throw.");
  }
  if (!(actual instanceof errorType))
    throw new MjsUnitAssertionError(
        "Expected " + run + "() to throw " + errorType.name +
        ", but threw '" + actual + "'");
  if (message !== void 0 && actual.message !== message)
    throw new MjsUnitAssertionError(
        "Expected " + run + "() to throw '" + message + "', but threw '" +
        actual.message + "'");
};

function assertEqualsAsync(expected, run, msg) {
  var actual;
  var hadValue = false;
  var hadError = false;
  var promise = run();

  if (typeof promise !== "object" || typeof promise.then !== "function") {
    throw new MjsUnitAssertionError(
        "Expected " + run.toString() +
        " to return a Promise, but it returned " + PrettyPrint(promise));
  }

  promise.then(function(value) { hadValue = true; actual = value; },
               function(error) { hadError = true; actual = error; });

  assertFalse(hadValue || hadError);

60
  %PerformMicrotaskCheckpoint();
61 62 63 64 65 66 67 68 69 70 71 72

  if (hadError) throw actual;

  assertTrue(
      hadValue, "Expected '" + run.toString() + "' to produce a value");

  assertEquals(expected, actual, msg);
};

assertEquals(undefined, this.AsyncFunction);
let AsyncFunction = (async function() {}).constructor;

73 74 75 76 77 78 79 80 81
// The AsyncFunction Constructor is the %AsyncFunction% intrinsic object and
// is a subclass of Function.
// (https://tc39.github.io/ecmascript-asyncawait/#async-function-constructor)
assertEquals(Object.getPrototypeOf(AsyncFunction), Function);
assertEquals(Object.getPrototypeOf(AsyncFunction.prototype),
             Function.prototype);
assertTrue(async function() {} instanceof Function);


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
// Let functionPrototype be the intrinsic object %AsyncFunctionPrototype%.
async function asyncFunctionForProto() {}
assertEquals(AsyncFunction.prototype,
             Object.getPrototypeOf(asyncFunctionForProto));
assertEquals(AsyncFunction.prototype,
             Object.getPrototypeOf(async function() {}));
assertEquals(AsyncFunction.prototype, Object.getPrototypeOf(async () => {}));
assertEquals(AsyncFunction.prototype,
             Object.getPrototypeOf({ async method() {} }.method));
assertEquals(AsyncFunction.prototype, Object.getPrototypeOf(AsyncFunction()));
assertEquals(AsyncFunction.prototype,
             Object.getPrototypeOf(new AsyncFunction()));

// AsyncFunctionCreate does not produce an object with a Prototype
assertEquals(undefined, asyncFunctionForProto.prototype);
assertEquals(false, asyncFunctionForProto.hasOwnProperty("prototype"));
assertEquals(undefined, (async function() {}).prototype);
assertEquals(false, (async function() {}).hasOwnProperty("prototype"));
assertEquals(undefined, (async() => {}).prototype);
assertEquals(false, (async() => {}).hasOwnProperty("prototype"));
assertEquals(undefined, ({ async method() {} }).method.prototype);
assertEquals(false, ({ async method() {} }).method.hasOwnProperty("prototype"));
assertEquals(undefined, AsyncFunction().prototype);
assertEquals(false, AsyncFunction().hasOwnProperty("prototype"));
assertEquals(undefined, (new AsyncFunction()).prototype);
assertEquals(false, (new AsyncFunction()).hasOwnProperty("prototype"));

assertEquals(1, async function(a) { await 1; }.length);
assertEquals(2, async function(a, b) { await 1; }.length);
assertEquals(1, async function(a, b = 2) { await 1; }.length);
assertEquals(2, async function(a, b, ...c) { await 1; }.length);

assertEquals(1, (async(a) => await 1).length);
assertEquals(2, (async(a, b) => await 1).length);
assertEquals(1, (async(a, b = 2) => await 1).length);
assertEquals(2, (async(a, b, ...c) => await 1).length);

assertEquals(1, ({ async f(a) { await 1; } }).f.length);
assertEquals(2, ({ async f(a, b) { await 1; } }).f.length);
assertEquals(1, ({ async f(a, b = 2) { await 1; } }).f.length);
assertEquals(2, ({ async f(a, b, ...c) { await 1; } }).f.length);

assertEquals(1, AsyncFunction("a", "await 1").length);
assertEquals(2, AsyncFunction("a", "b", "await 1").length);
assertEquals(1, AsyncFunction("a", "b = 2", "await 1").length);
assertEquals(2, AsyncFunction("a", "b", "...c", "await 1").length);

assertEquals(1, (new AsyncFunction("a", "await 1")).length);
assertEquals(2, (new AsyncFunction("a", "b", "await 1")).length);
assertEquals(1, (new AsyncFunction("a", "b = 2", "await 1")).length);
assertEquals(2, (new AsyncFunction("a", "b", "...c", "await 1")).length);

// AsyncFunction.prototype[ @@toStringTag ]
var descriptor =
    Object.getOwnPropertyDescriptor(AsyncFunction.prototype,
                                    Symbol.toStringTag);
assertEquals("AsyncFunction", descriptor.value);
assertEquals(false, descriptor.enumerable);
assertEquals(false, descriptor.writable);
assertEquals(true, descriptor.configurable);

assertEquals(1, AsyncFunction.length);

// Let F be ! FunctionAllocate(functionPrototype, Strict, "non-constructor")
async function asyncNonConstructorDecl() {}
147 148 149 150 151 152 153 154
assertThrows(() => new asyncNonConstructorDecl(), TypeError);
assertThrows(() => asyncNonConstructorDecl.caller, TypeError);
assertThrows(() => asyncNonConstructorDecl.arguments, TypeError);

assertThrows(() => new (async function() {}), TypeError);
assertThrows(() => (async function() {}).caller, TypeError);
assertThrows(() => (async function() {}).arguments, TypeError);

155 156 157
assertThrows(
    () => new ({ async nonConstructor() {} }).nonConstructor(), TypeError);
assertThrows(
158
    () => ({ async nonConstructor() {} }).nonConstructor.caller, TypeError);
159
assertThrows(
160 161 162 163 164 165 166 167 168 169 170 171 172
    () => ({ async nonConstructor() {} }).nonConstructor.arguments, TypeError);

assertThrows(() => new (() => "not a constructor!"), TypeError);
assertThrows(() => (() => 1).caller, TypeError);
assertThrows(() => (() => 1).arguments, TypeError);

assertThrows(() => new (AsyncFunction()), TypeError);
assertThrows(() => AsyncFunction().caller, TypeError);
assertThrows(() => AsyncFunction().arguments, TypeError);

assertThrows(() => new (new AsyncFunction()), TypeError);
assertThrows(() => (new AsyncFunction()).caller, TypeError);
assertThrows(() => (new AsyncFunction()).arguments, TypeError);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

// Normal completion
async function asyncDecl() { return "test"; }
assertEqualsAsync("test", asyncDecl);
assertEqualsAsync("test2", async function() { return "test2"; });
assertEqualsAsync("test3", async () => "test3");
assertEqualsAsync("test4", () => ({ async f() { return "test4"; } }).f());
assertEqualsAsync("test5", () => AsyncFunction("no", "return 'test' + no;")(5));
assertEqualsAsync("test6",
                  () => (new AsyncFunction("no", "return 'test' + no;"))(6));

class MyError extends Error {};

// Throw completion
async function asyncDeclThrower(e) { throw new MyError(e); }
assertThrowsAsync(() => asyncDeclThrower("boom!"), MyError, "boom!");
assertThrowsAsync(
  () => (async function(e) { throw new MyError(e); })("boom!!!"),
  MyError, "boom!!!");
assertThrowsAsync(
  () => (async e => { throw new MyError(e) })("boom!!"), MyError, "boom!!");
assertThrowsAsync(
  () => ({ async thrower(e) { throw new MyError(e); } }).thrower("boom!1!"),
  MyError, "boom!1!");
assertThrowsAsync(
  () => AsyncFunction("msg", "throw new MyError(msg)")("boom!2!!"),
  MyError, "boom!2!!");
assertThrowsAsync(
  () => (new AsyncFunction("msg", "throw new MyError(msg)"))("boom!2!!!"),
  MyError, "boom!2!!!");

function resolveLater(value) { return Promise.resolve(value); }
function rejectLater(error) { return Promise.reject(error); }

// Resume after Normal completion
var log = [];
async function resumeAfterNormal(value) {
  log.push("start:" + value);
  value = await resolveLater(value + 1);
  log.push("resume:" + value);
  value = await resolveLater(value + 1);
  log.push("resume:" + value);
  return value + 1;
}

assertEqualsAsync(4, () => resumeAfterNormal(1));
assertEquals("start:1 resume:2 resume:3", log.join(" "));

var O = {
  async resumeAfterNormal(value) {
    log.push("start:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    return value + 1;
  }
};
log = [];
assertEqualsAsync(5, () => O.resumeAfterNormal(2));
assertEquals("start:2 resume:3 resume:4", log.join(" "));

var resumeAfterNormalArrow = async (value) => {
  log.push("start:" + value);
  value = await resolveLater(value + 1);
  log.push("resume:" + value);
  value = await resolveLater(value + 1);
  log.push("resume:" + value);
  return value + 1;
};
log = [];
assertEqualsAsync(6, () => resumeAfterNormalArrow(3));
assertEquals("start:3 resume:4 resume:5", log.join(" "));

var resumeAfterNormalEval = AsyncFunction("value", `
    log.push("start:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    return value + 1;`);
log = [];
assertEqualsAsync(7, () => resumeAfterNormalEval(4));
assertEquals("start:4 resume:5 resume:6", log.join(" "));

var resumeAfterNormalNewEval = new AsyncFunction("value", `
    log.push("start:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    value = await resolveLater(value + 1);
    log.push("resume:" + value);
    return value + 1;`);
log = [];
assertEqualsAsync(8, () => resumeAfterNormalNewEval(5));
assertEquals("start:5 resume:6 resume:7", log.join(" "));

// Resume after Throw completion
async function resumeAfterThrow(value) {
  log.push("start:" + value);
  try {
    value = await rejectLater("throw1");
  } catch (e) {
    log.push("resume:" + e);
  }
  try {
    value = await rejectLater("throw2");
  } catch (e) {
    log.push("resume:" + e);
  }
  return value + 1;
}

log = [];
assertEqualsAsync(2, () => resumeAfterThrow(1));
assertEquals("start:1 resume:throw1 resume:throw2", log.join(" "));

var O = {
  async resumeAfterThrow(value) {
    log.push("start:" + value);
    try {
      value = await rejectLater("throw1");
    } catch (e) {
      log.push("resume:" + e);
    }
    try {
      value = await rejectLater("throw2");
    } catch (e) {
      log.push("resume:" + e);
    }
    return value + 1;
  }
}
log = [];
assertEqualsAsync(3, () => O.resumeAfterThrow(2));
assertEquals("start:2 resume:throw1 resume:throw2", log.join(" "));

var resumeAfterThrowArrow = async (value) => {
  log.push("start:" + value);
  try {
    value = await rejectLater("throw1");
  } catch (e) {
    log.push("resume:" + e);
  }
  try {
    value = await rejectLater("throw2");
  } catch (e) {
    log.push("resume:" + e);
  }
 return value + 1;
};

log = [];

assertEqualsAsync(4, () => resumeAfterThrowArrow(3));
assertEquals("start:3 resume:throw1 resume:throw2", log.join(" "));

var resumeAfterThrowEval = AsyncFunction("value", `
    log.push("start:" + value);
    try {
      value = await rejectLater("throw1");
    } catch (e) {
      log.push("resume:" + e);
    }
    try {
      value = await rejectLater("throw2");
    } catch (e) {
      log.push("resume:" + e);
    }
    return value + 1;`);
log = [];
assertEqualsAsync(5, () => resumeAfterThrowEval(4));
assertEquals("start:4 resume:throw1 resume:throw2", log.join(" "));

var resumeAfterThrowNewEval = new AsyncFunction("value", `
    log.push("start:" + value);
    try {
      value = await rejectLater("throw1");
    } catch (e) {
      log.push("resume:" + e);
    }
    try {
      value = await rejectLater("throw2");
    } catch (e) {
      log.push("resume:" + e);
    }
    return value + 1;`);
log = [];
assertEqualsAsync(6, () => resumeAfterThrowNewEval(5));
assertEquals("start:5 resume:throw1 resume:throw2", log.join(" "));
362 363 364

async function foo() {}
assertEquals("async function foo() {}", foo.toString());
365
assertEquals("async function () {}", async function () {}.toString());
366 367 368
assertEquals("async x => x", (async x => x).toString());
assertEquals("async x => { return x }", (async x => { return x }).toString());
class AsyncMethod { async foo() { } }
369 370 371 372
assertEquals("async foo() { }",
             Function.prototype.toString.call(AsyncMethod.prototype.foo));
assertEquals("async foo() { }",
             Function.prototype.toString.call({async foo() { }}.foo));
373 374 375

// Async functions are not constructible
assertThrows(() => class extends (async function() {}) {}, TypeError);
376 377 378 379 380 381 382 383 384 385

// Regress v8:5148
assertEqualsAsync("1", () => (async({ a = NaN }) => a)({ a: "1" }));
assertEqualsAsync(
    "10", () => (async(foo, { a = NaN }) => foo + a)("1", { a: "0" }));
assertEqualsAsync("2", () => (async({ a = "2" }) => a)({ a: undefined }));
assertEqualsAsync(
    "20", () => (async(foo, { a = "0" }) => foo + a)("2", { a: undefined }));
assertThrows(() => eval("async({ foo = 1 })"), SyntaxError);
assertThrows(() => eval("async(a, { foo = 1 })"), SyntaxError);
386

387
// https://bugs.chromium.org/p/chromium/issues/detail?id=638019
388 389 390 391 392
async function gaga() {
  let i = 1;
  while (i-- > 0) { await 42 }
}
assertDoesNotThrow(gaga);
393 394 395 396 397 398 399 400 401 402 403 404


{
  let log = [];
  async function foo() {
    try {
      Promise.resolve().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
405
  %PerformMicrotaskCheckpoint();
406 407 408 409 410 411 412 413 414 415 416 417 418
  assertEquals(["b", "a", "c"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return Promise.resolve().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
419
  %PerformMicrotaskCheckpoint();
420 421 422 423 424 425 426 427 428 429 430 431 432
  assertEquals(["b", "a", "c"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return await Promise.resolve().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
433
  %PerformMicrotaskCheckpoint();
434 435 436 437 438 439 440 441 442 443 444 445 446 447
  assertEquals(["a", "b", "c"], log);
}


{
  let log = [];
  async function foo() {
    try {
      Promise.resolve().then().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
448
  %PerformMicrotaskCheckpoint();
449 450 451 452 453 454 455 456 457 458 459 460 461
  assertEquals(["b", "c", "a"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return Promise.resolve().then().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
462
  %PerformMicrotaskCheckpoint();
463 464 465 466 467 468 469 470 471 472 473 474 475
  assertEquals(["b", "a", "c"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return await Promise.resolve().then().then(() => log.push("a"))
    } finally {
      log.push("b");
    }
  }
  foo().then(() => log.push("c"));
476
  %PerformMicrotaskCheckpoint();
477 478 479 480 481 482 483 484 485 486 487 488 489 490
  assertEquals(["a", "b", "c"], log);
}


{
  let log = [];
  async function foo() {
    try {
      Promise.resolve().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
491
  %PerformMicrotaskCheckpoint();
492 493 494 495 496 497 498 499 500 501 502 503 504
  assertEquals(["b", "a", "c"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return Promise.resolve().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
505
  %PerformMicrotaskCheckpoint();
506 507 508 509 510 511 512 513 514 515 516 517 518
  assertEquals(["b", "a", "c"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return await Promise.resolve().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
519
  %PerformMicrotaskCheckpoint();
520 521 522 523 524 525 526 527 528 529 530 531 532 533
  assertEquals(["a", "b", "c"], log);
}


{
  let log = [];
  async function foo() {
    try {
      Promise.resolve().then().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
534
  %PerformMicrotaskCheckpoint();
535 536 537 538 539 540 541 542 543 544 545 546 547
  assertEquals(["b", "c", "a"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return Promise.resolve().then().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
548
  %PerformMicrotaskCheckpoint();
549 550 551 552 553 554 555 556 557 558 559 560 561
  assertEquals(["b", "c", "a"], log);
}

{
  let log = [];
  async function foo() {
    try {
      return await Promise.resolve().then().then(() => log.push("a"))
    } finally {
      return log.push("b");
    }
  }
  foo().then(() => log.push("c"));
562
  %PerformMicrotaskCheckpoint();
563 564
  assertEquals(["a", "b", "c"], log);
}
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

{
  function f1() {
    var x;
    with ({get await() { return [42] }}) {
      x = await
      [0];
    };
    return x;
  }

  assertEquals(42, f1());
  async function f2() {
    var x;
    with ({get await() { return [42] }}) {
      x = await
      [0];
    };
    return x;
  }

  var ans;
  f2().then(x => ans = x).catch(e => ans = e);
588
  %PerformMicrotaskCheckpoint();
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  assertEquals([0], ans);
}

{
  function f1() {
    var x, y;
    with ({get await() { return [42] }}) {
      x = await
      y = 1
    };
    return y;
  }

  assertEquals(1, f1());
}