[英]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
函数
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.log
是async
您也可以向它传递任何值。
Simplest way to print promise value....打印 promise 值的最简单方法....
some_promise().then(console.log);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.