await is only valid in async function
這個錯誤的意思是await只能放到async函式內部,言下之意:
- await必須放到函式裡
- 函式必須有async修飾符
錯誤1: 沒有放到函式裡
const myFun = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
},1000)
})
}
// 錯誤: 沒有放在函式裡
res1 = await myFun();
console.log(res1);
// SyntaxError: await is only valid in async function
錯誤2: 函式沒有async修飾符
const myFun = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
},1000)
})
}
// 錯誤: 函式沒有async修飾符
const myFun2 = () => {
res1 = await myFun();
console.log(res1);
}
myFun2();
// SyntaxError: await is only valid in async function
正確寫法
const myFun = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
},1000)
})
}
const myFun2 = async () => {
res1 = await myFun();
console.log(res1);
}
myFun2();
// 1
相關文章
- Async/awaitAI
- Async +AwaitAI
- 理解 async/awaitAI
- async和awaitAI
- Async 和 AwaitAI
- 淺談async/awaitAI
- async await詳解AI
- JavaScript Promises, async/awaitJavaScriptPromiseAI
- decorator, async/await, generatorAI
- 好用的 async/awaitAI
- C# async / awaitC#AI
- Hey async, await meAI
- JavaScript async await 使用JavaScriptAI
- 【譯】Async/Await(三)——Aysnc/Await模式AI模式
- [譯]JavaScript Symbols, Iterators, Generators, Async/Await, and Async IteratorsJavaScriptSymbolAI
- 理解 js的 async/awaitJSAI
- 重學JS:async/awaitJSAI
- 深入理解 async / awaitAI
- 理解JavaScript的async/awaitJavaScriptAI
- 小程式使用 async awaitAI
- 【譯】Async/Await(二)——FuturesAI
- 理解Task和和async awaitAI
- 理解 JavaScript 的 async/awaitJavaScriptAI
- WPF WebClient EAP async awaitWebclientAI
- async和await的使用AI
- [Javascript] Promise question with async awaitJavaScriptPromiseAI
- Async,Await 深入原始碼解析AI原始碼
- 如何講清楚async和await?AI
- 非同步神器async-await非同步AI
- 【譯】JavaScript中的async/awaitJavaScriptAI
- Async/Await 代替 Promise.all()AIPromise
- [譯]帶你理解 Async/awaitAI
- Promise與async/await與GeneratorPromiseAI
- async/await使用深入詳解AI
- 【譯】Async/Await(四)—— PinningAI
- 【譯】Async/Await(五)—— Executors and WakersAI
- ES6 - async&awaitAI
- JavaScript 的 async/await 理解(4)JavaScriptAI