简体   繁体   中英

Console.log and await

I noticed that console.log(await some_promise()); works fine but if I make my own log function it doesn't work and it says that await only works in async functions. But then how come it works in console.log()? If console.log is async, then how come it works without promises too?

But then how come it works in console.log()

It doesn't. Arguments passed to a function are always evaluated before the function is called. Ie await some_promise() is evaluated before console.log is called, not in it. console.log is not async . Your code is equivalent to

const result = await some_promise();
console.log(result);

or

some_promise.then(result => console.log(result))

console.log doesn't know anything about the fact that the value you pass to it came from a promise.

If console.log is async, then how come it works without promises too?

An async function

  1. returns a promise
  2. allows you to use await to unwrap promises.

That's all. It doesn't restrict which values you can pass to it. So even if console.log was async you could pass any value to it.

Simplest way to print promise value....

some_promise().then(console.log);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM