基本规则
async 表示
这是一个async函数,await只能用在这个函数里面。await 表示在这里
等待promise返回结果了,再继续执行。await 后面跟着的
应该是一个promise对象
talk is cheap ,show me the code
var sleep = function (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
time > 2000 ? resolve("greater than 2000"): reject("less than 2000");
}, time);
});
};
var start = async function (time) {
console.log('start');
await sleep(time).then(function(v){
console.log('resolved: '+ v);
},function(e){
console.log('rejected:'+e)
});
console.log('end');
};运行①:
start(3000);结果:

运行②:
start(1000);结果:

本文介绍了JavaScript中async函数的基本使用方法及await关键字的作用。通过具体示例讲解如何利用这些特性实现异步操作,并展示了如何处理promise的成功与失败情况。
377

被折叠的 条评论
为什么被折叠?



