全部完成的Promise (Promise allSettled)
MengZhaoFly opened this issue · 0 comments
MengZhaoFly commented
题目描述
/*
用 promise 实现以下功能。
具体: fn1和fn2都是异步函数,f1、fn2同时执行,并且fn1、fn2的结果是 fn3的参数。当fn1或者fn2发生错误时,fn3照常执行,此时的参数为空。
*/
eg:
fn1 = async() => {
// 发送请求
const data = await sendRquest1();
return data;
}
fn2 = async() => {
// 发送请求
const data = await sendRquest2();
return data;
}
解答
function sendRquest1(t) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(t)
}, t)
})
}
fn1 = async() => {
// 发送请求
const data = await sendRquest1(1000);
return data;
}
fn2 = async() => {
// 发送请求
const data = await sendRquest1(2000);
return data;
}
Promise.allSettled([fn1(), fn2()]).then(res => res.map(r => {
if (r.status === 'rejected') return null;
return r.value;
})).then(fn3)
function fn3() {
console.log(arguments)
}
出处
作者:牛客442409485号
链接:https://www.nowcoder.com/discuss/462373
来源:牛客网