tc39/proposal-async-await

A question about async await with native promise.

JiaLiPassion opened this issue · 7 comments

The following code

async function detect() { }
const r = detect();
const nativeThen = r.__proto__.then;
r.__proto__.then = function () {
  console.log('promise.then');
  return nativeThen.apply(this, arguments);
}

async function test1() {
  console.log('before await');
  const r = await test();
  console.log('after await');
}

test1();
console.log('end');

// the output will be
// before await
// end
// promise.then, question is why promise.then is after end?
// after await 

The nativePromise.then will be executed after end, I don't understand why, any help will be appreciated.

Because the async function immediately suspends on the first await.

@ljharb, thanks, is that possible to know the timing when an await operation is executed? I mean before the context go outside of the test1 function.

I’m not sure i know what you’re asking. An async function executes synchronously up until the first await, and then returns a Promise. The rest executes on future ticks.

@ljharb. Sorry I didn't provide the context. I want to implement zone.js for native async/await to keep the async context.
so in this code

async function test1() {
  console.log('before await', Zone.current.name); // testZone 
  const r = await test();
  console.log('after await'); // expect testZone 
}

testZone.run(test1);
console.log('end');

The purpose is after await, zone.js can still keep the async context before await.
So I need some trigger/hook to be executed when await test() is called.

Without being able to wrap the value being awaited, I’m not sure if that hook exists - this is really more of a question for the zones proposal tho, not for async/await.

I know, I also asked there, in the example, the function test1 can be wrapped because zone run it directly. But in the following example,

async function test1() {
  console.log('before await', Zone.current.name); // testZone 
  const r = await test();
  console.log('after await'); // expect testZone 
}

function test2() {
  test1();
}

testZone.run(test2);

We have no idea about the test1.

So I just wonder if there any Native Promise init hook like Chrome v8 provided in c++.

This proposal is stage 4, and has been merged into the spec as of ES2017.