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/Await(三)——Aysnc/Await模式AI模式
- async await詳解AI
- 淺談async/awaitAI
- JavaScript async await 使用JavaScriptAI
- JavaScript Promises, async/awaitJavaScriptPromiseAI
- 小程式使用 async awaitAI
- 理解JavaScript的async/awaitJavaScriptAI
- 深入理解 async / awaitAI
- WPF WebClient EAP async awaitWebclientAI
- 重學JS:async/awaitJSAI
- 理解Task和和async awaitAI
- 理解 js的 async/awaitJSAI
- [Javascript] Promise question with async awaitJavaScriptPromiseAI
- async和await的使用AI
- 【譯】Async/Await(二)——FuturesAI
- 【譯】Async/Await(四)—— PinningAI
- [譯]JavaScript Symbols, Iterators, Generators, Async/Await, and Async IteratorsJavaScriptSymbolAI
- JavaScript 的 async/await 理解(4)JavaScriptAI
- 非同步神器async-await非同步AI
- ES6 - async&awaitAI
- 使用async await 封裝 axiosAI封裝iOS
- 如何正確使用async/await?AI
- Promise和async await詳解PromiseAI
- 理解 es7 async awaitAI
- [譯文] JavaScript async 和 awaitJavaScriptAI
- Async/Await 代替 Promise.all()AIPromise
- 如何講清楚async和await?AI
- Async,Await 深入原始碼解析AI原始碼
- [譯]帶你理解 Async/awaitAI
- 【譯】JavaScript中的async/awaitJavaScriptAI
- ES2017 —— async await原理AI
- Promise/async/await 研究筆記PromiseAI筆記
- generator函式與async/await函式AI
- async/await使用深入詳解AI