javascript - Async/Await报错
问题描述
这段代码问题在哪,一运行就报错
var sleep = async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {resolve(para * para) }, 1000)}) } var errorSleep =async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {reject(’ ErrorSleep’) }, 1000)}) } try {var result1 = await sleep(1);var result2 = await errorSleep(4);var result3 = await sleep(1);console.log(’result1: ’, result1)console.log(’result2: ’, result2)console.log(’result3: ’, result3) } catch (err) {console.log(’err: ’, err)console.log(’result1: ’, result1)console.log(’result2: ’, result2)console.log(’result3: ’, result3) }

问题解答
回答1:await 只能在 async 包装的函数里面用。就和yield只能在generator函数里面用一样。
回答2:楼上不是说了吗,丢到async函数里。
var sleep = async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {resolve(para * para) }, 1000)}) } var errorSleep =async function(para) {return new Promise(function(resolve, reject) { setTimeout(function() {reject(’ ErrorSleep’) }, 1000)}) }//一样丢到async函数里 var af = async function() {try { var result1 = await sleep(1); var result2 = await errorSleep(4); var result3 = await sleep(1); console.log(’result1: ’, result1) console.log(’result2: ’, result2) console.log(’result3: ’, result3)} catch (err) { console.log(’err: ’, err) console.log(’result1: ’, result1) console.log(’result2: ’, result2) console.log(’result3: ’, result3)} } af();回答3:
await 只能在 async 函数(函数,函数表达式,箭头函数) 中使用,所以你只需要写个 async 函数把那段代码包起来就好了,我比较喜欢写 main 函数而不是直接在全局作用域内运行
async function main() { try {var result1 = await sleep(1);var result2 = await errorSleep(4);var result3 = await sleep(1);console.log('result1: ', result1);console.log('result2: ', result2);console.log('result3: ', result3); } catch (err) {console.log('err: ', err);console.log('result1: ', result1);console.log('result2: ', result2);console.log('result3: ', result3); }}// 记得调用main();
另外也可以使用 async IIFE 表达式,比如
// IIFE 函数表达式(async function() { // todo main process})();// IIFE Lambda 表达式(箭头函数表达式)(async () => { // todo main process})();
相关文章:
1. html - 这种错位的时间轴怎么布局,然后用css实现?2. CSS3 flex 如何让高度不等的同排等高?3. 网页爬虫 - python requests爬虫,如何post payload4. python - 如何用pandas处理分钟数据变成小时线?5. ionic 项目 ionic build android -release 打包时报错6. 请教,关于python字典,合并相同值的键的实现方法7. android - viewpager问题PagerTabStrip样式8. angular.js - 如何控制ngrepeat输出的个数9. javascript - 关于ajax请求问题!10. mysql_replication - mysql读写分离时如果单台写库也无法满足性能怎么解决

网公网安备