Promise.all()和Promise.race()

promise.all()

Promise.all()方法会发起并行的promise异步操作,等所有的异步操作全部结束,才会执行下一步的.then()操作(等待机制),实例代码:

import thenfs from 'then-fs'

const promises = [
	thenfs.readFile('./text/1.txt', 'utf8'),
	thenfs.readFile('./text/2.txt', 'utf8'),
	thenfs.readFile('./text/3.txt', 'utf8'),
]

//这里res的顺序就是promise传入对象中的顺序
Promise.all(promises).then((res) => {
    
    
	console.log(res)
})

promise.race()

Promise.race()方法会发起并行的Promise异步操作,只要任何一个异步操作完成,就立即执行下一步的.then()操作(赛跑机制),示例代码如下:

它只会输出返回最快的一个promise

//Promise.race()
const promises = [
	thenfs.readFile('./text/1.txt', 'utf8'),
	thenfs.readFile('./text/2.txt', 'utf8'),
	thenfs.readFile('./text/3.txt', 'utf8'),
]
Promise.race(promises).then((res) => {
    
    
	console.log(res)
})

猜你喜欢

转载自blog.csdn.net/ice_stone_kai/article/details/124062297