异步调用:
initUserId().then(res => {
console.log(res)
})
可以写成这样没错吧:
const res = await initUserId()
但是实际在执行的时候(执行npx tsx test05.ts
),报错:
node:internal/process/esm_loader:40
internalBinding('errors').triggerUncaughtException(
^
Error: Transform failed with 1 error:
/Users/john/Desktop/typescript-demo-01/ts-test/test05.ts:20:12: ERROR: Top-level await is currently not supported with the "cjs" output format
请问这是什么问题呢?
完整代码如下:
const initUserId = async (): Promise<string> => {
const fetchUserId = async(): Promise<string> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return new Promise((resolve, _reject) => {
setTimeout(() => {
const userId = '222';
resolve(userId);
}, 1000);
})
}
const userId = await fetchUserId()
return userId
}
initUserId().then(res => {
console.log(res)
})
const res = await initUserId()
console.log(res)
export {}