promise函数有几种状态
- promise函数有三种状态,分别是初始化,成功状态,失败状态
异步解决方案有哪几种
- 使用回调函数解决异步问题
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('请输入你的名字。');
callback(name);
}
processUserInput(greeting);
- 事件发布订阅解决异步问题
*---------2.事件发布订阅:---------*/
document.body.addEventListener('click',function(){
alert('订阅了');
},false);
document.body.click();
- 使用Promise函数解决异步问题
let promise = new Promise(function (resolve, reject) {
fs.readFile('./1.txt', 'utf8', function (err, data) {
resolve(data)
})
})
promise
.then(function (data) {
console.log(data)
})
- Generator
function * count() {
yield 1
yield 2
return 3
}
var c = count()
console.log(c.next())
console.log(c.next())
console.log(c.next())
console.log(c.next())
- async/await修饰promise函数搭配使用
async function read() {
let readA = await readFile('data/a.txt')
let readB = await readFile('data/b.txt')
let readC = await readFile('data/c.txt')
console.log(readA)
console.log(readB)
console.log(readC)
}
read()
Promise方法的使用
- promise.allSettled()应用场景:当我们需要同时接收多个请求时,需要使用Promise.allSettled()这个方法来同时获取数据,比如做一些图表的功能,需要同时请求几个数据,如果不同时出现图表就会一只loading,这个时候就需要用Promise.allSettled()方法同时获取。
- promise.race()应用场景:请求超时时需要拿到返回的最快的数据
const p1 = 'dawd'
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('第一个数据')
},200)
})
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('第二个数据')
},200)
})
Promise.all([p1, p2, p3]).then((val)=>{
console.log(val);
})
Promise.allSettled([p1, p2, p3]).then((val)=>{
console.log(val);
})
Promise.race([p1, p2, p3]).then((val)=>{
console.log(val);
})
Promise.any([p2, p3]).then((val)=>{
console.log(val);
})
new Promise((resolve, reject) => {
reject()
}).then(()=>{
}).catch(()=>{
}).finally(()=>{
console.log('调用了finally方法');
})
setTimeout(()=>{
console.log(1);
});
console.log(2);
new Promise((resolve)=>{
console.log(3);
resolve()
}).then(()=>{
console.log(4);
});
const fn1 = () =>{
console.log(5);
};
async function fn2(){
const res = await fn1()
console.log(6);
}
fn2()
console.log(7);