一秒看懂的 async/await

基本规则

  1. async 表示这是一个async函数await只能用在这个函数里面

  2. await 表示在这里等待promise返回结果了,再继续执行。

  3. 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);

结果:






猜你喜欢

转载自blog.csdn.net/arsaycode/article/details/80333425