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)
}
三叔2017-06-17 09:17:45
await can only be used in async wrapped functions.
Just like yield, it can only be used in the generator function.
为情所困2017-06-17 09:17:45
Didn’t I say it above? Throw it into the async function.
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();
黄舟2017-06-17 09:17:45
await
can only be used in async
functions (functions, function expressions, arrow functions), so you only need to write an async
function to wrap that code. I prefer to write main
function instead of running directly in the global scope
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();
In addition, you can also use async
IIFE expression, such as
// IIFE 函数表达式
(async function() {
// todo main process
})();
// IIFE Lambda 表达式(箭头函数表达式)
(async () => {
// todo main process
})();