Rumah > Soal Jawab > teks badan
Apakah masalah dengan kod ini. Ia melaporkan ralat sebaik sahaja ia dijalankan
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
menunggu hanya boleh digunakan dalam fungsi yang dibalut async.
Sama seperti hasil, ia hanya boleh digunakan dalam fungsi penjana.
为情所困2017-06-17 09:17:45
Bukankah saya telah mengatakannya di tingkat atas?
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
只能在 async
函数(函数,函数表达式,箭头函数) 中使用,所以你只需要写个 async
函数把那段代码包起来就好了,我比较喜欢写 main
berfungsi dan bukannya berjalan terus dalam skop global
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();
Selain itu, anda juga boleh menggunakan async
ekspresi IIFE, seperti
// IIFE 函数表达式
(async function() {
// todo main process
})();
// IIFE Lambda 表达式(箭头函数表达式)
(async () => {
// todo main process
})();