基本规则
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);
结果: