這段程式碼問題在哪,一運行就報錯
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
樓上不是說了嗎,丟到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();
黄舟2017-06-17 09:17:45
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
})();