Promise异步使用(async & await)

Promise 等同于 async…await,async-await 组合返回一个Promise异步链

    async是一个加在函数前的修饰符,被async定义的函数会默认返回一个Promise对象resolve的值。因此对async函数可以直接then,返回值就是then方法传入的函数

// 1、await 修饰非promise,直接返回表达式的结果
async function a() {
    
    
    return await "1"
}
console.log(a()) // 返回一个promise对象
a().then(a => {
    
    console.log(a)})

// 2、await 修饰promise方法:可以获取Promise中返回的内容(resolve或reject的参数),且取到值后语句才会往下执行
// 取到的值需要返回

async function log(t) {
    
    
    return await t
}
async function a() {
    
    
 return await log(1)
}
a().then(a => {
    
    console.log(a)})

Promise有两个原型,.then(() => {}) 处理返回成功的数据;.catch(e => {}) 处理返回失败的数据

关于Promise:简单的定义和调用

// 定义
<script>
	function test1(type) {
    
    
	    return new Promise((resolve, reject) => {
    
    
	      if(type === 1) {
    
    
	        resolve('success. resloved result data')
	      }
	      if(type === 2) {
    
    
	        reject('error reject.')
	      }  
	    })
	}
	
	// 调用
	test1(2).then(d => {
    
    
	    console.log('成功:', d)
	}).catch (e => {
    
    
	    console.log('异常:', e)
	})
	
	// ===> 等同于 async ... await ... (async await 需要成对出现)
	// async 是需要同步的方法
	// await 是同步方法内需要等待的异步操作
	
	async function test2(type) {
    
    
	    if(type === 1) {
    
    
	        return await "success data!"
	    }
	    if(type === 2) {
    
    
	        return await "error data!"
	    }
	}
	
	// 调用
	test2(1).then(d => {
    
    
	    console.log('返回:', d)
	}).catch (e => {
    
    
	    console.log('异常:', e)
	})
</script>

关于Promise:for循环中进行异步调用
for循环中如果不对异步操作做同步处理,结果不会是理想的:这就是异步操作需要以同步的方式去执行,因为下一步的执行需要等待上一步的结果。

<script>

    (function() {
    
    
        start()
    })();

    async function start() {
    
    
        for(let i = 0; i < 10; i++) {
    
    
            let r = await get(i)
            console.log(r)
        }
    }

    // 需要进行的异步操作
    async function get(param) {
    
    
        // return await param
        return await yb(param)  // 异步的方法   
    }

    async function yb(param) {
    
    
        // 假设做了其他的异步处理
        return await 'T. ' + param
    }
</script>

// ===> 还可以这么写
<script>
    (function() {
    
    
        let ss = start()

        ss.then(d => {
    
    
            console.log('ss:', d)
        })
    })();

    async function start() {
    
    
    	// var pp = new Promise(r => { r() }) ⇒ 等同于.
        var pp = Promise.resolve()
        // 循环中的异步操作 
        for(let i = 0, total = 2; i < total; i++) {
    
    
            pp = pp.then(() => {
    
    
                sleep(2)    // 模拟一个延时操作
                total = 5  // 假设循序的次数是在某一次调用之后修改的,如果不await,直接就将所有的异步链完成,循环结束
                console.log('i:', i)
                return Promise.resolve('O_O! ')
            })
            // 可以尝试看去掉 await pp后产生的打印结果,就知道为什么要在循环中进行同步处理了
            await pp
        }
        // 结束
        pp.then((d) => {
    
    
            console.log('OK.', d)
        })
        return pp
    }

    function sleep(s) {
    
    
      let now = new Date();
      let exitTime = now.getTime() + Math.random() * s * 1000;
      while (true) {
    
    
        now = new Date();
        if (now.getTime() > exitTime) return;
      }
    }
</script>

关于js线程同步异步可以参考文章:理解js中的同步和异步

猜你喜欢

转载自blog.csdn.net/dongzi_yu/article/details/126623530