【发布时间】:2019-07-05 12:43:06
【问题描述】:
非常直截了当的问题,我知道当我编写这样的异步函数时:
const res = (async () => 'hello')();
console.log(await res);
它应该记录:'hello'
但是,假设我想在异步函数中使结果超时,我必须创建一个新的 Promise,以便将超时回调包装在其中,如下所示:
const res = (async () =>
new Promise(resolve =>
setTimeout(
() => resolve('hello'), 1000
)
)
)();
console.log(await res);
好吧,如果 async 已经返回了一个 Promise,为什么我需要在一个已经是 Promise 的函数中创建一个新的 Promise 来做这么简单的事情呢? 我是否遗漏了什么,或者它确实是这样设计的? 如果我能以原生方式做这样的事情不是更好吗?甚至可能吗? 例如:
const res = (async () =>
setTimeout(
() => resolve('hello'), 1000
)
)();
console.log(await res);
【问题讨论】:
-
你不能,因为 Promise 链中没有可用的
resolve()函数。
标签: javascript typescript