简体   繁体   English

Console.log 并等待

[英]Console.log and await

I noticed that console.log(await some_promise());我注意到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.工作正常,但如果我创建自己的日志 function 它不起作用,它说等待只在异步函数中工作。 But then how come it works in console.log()?但是它怎么会在 console.log() 中起作用呢? If console.log is async, then how come it works without promises too?如果 console.log 是异步的,那么它怎么能在没有承诺的情况下工作呢?

But then how come it works in console.log()但是它是如何在 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.await some_promise()调用console.log之前被评估,而不是其中。 console.log is not async . console.log不是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. console.log对传递给它的值来自承诺的事实一无所知。

If console.log is async, then how come it works without promises too?如果 console.log 是异步的,那么它如何在没有承诺的情况下工作?

An async function async函数

  1. returns a promise返回一个承诺
  2. allows you to use await to unwrap promises.允许您使用await来解开承诺。

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.因此,即使console.logasync您也可以向它传递任何值。

Simplest way to print promise value....打印 promise 值的最简单方法....

some_promise().then(console.log);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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