What is the problem with this code? It reports an error as soon as it is run.
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) }

await can only be used in async wrapped functions.
Just like yield, it can only be used in the generator function.
Didn’t I say it above? Throw it into the async function.
awaitcan only be used inasyncfunctions (functions, function expressions, arrow functions), so you only need to write anasyncfunction to wrap that code. I prefer to writemainfunction instead of running directly in the global scopeIn addition, you can also use
asyncIIFE expression, such as