function fn() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let n = parseInt(Math.random() * 6 + 1, 10); //[1,7)
resolve(n);
}, 3000);
});
}
fn().then(
(x) => {
console.log("successfull", x);
},
() => {
"fail";
}
);
async/await
await只能放在async函数里面,否则直接报错。
function fn() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let n = parseInt(Math.random() * 6 + 1, 10); //[1,7)
resolve(n);
}, 3000);
});
}
async function test(){
let n = await fn();//如果这里没写括号,就不会执行这个fn函数
console.log(n)
}
test()
await后面接一个会return new Promise()的函数,并执行这个函数
另一个例子
function fn(guessNumber) {
return new Promise((resolve, reject) => {
setTimeout(() => {
let n = parseInt(Math.random() * 6 + 1, 10); //[1,7)
if (n > 3) {
if (guessNumber === "big") {
resolve(n);
} else {
reject(n);
}
} else {
if (guessNumber === "small") {
resolve(n);
} else {
reject(n);
}
}
}, 3000);
});
}
async function test() {
try {
let n = await fn("big");
console.log("you win");
} catch (error) {
console.log("you loss");
}
}
test();
面试题:为什么要用await?
为了更像是标准的同步函数(从上往下执行的)
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.