当前位置:网站首页>Promise.all 使用方法
Promise.all 使用方法
2022-08-04 05:36:00 【m0_67402026】
1.await 可以获得多个promise 的返回结果
2. Promise.all 返回的也是promise,所以可以直接await Promise.all();
1. 使用Promise
function fn(){
return new Promise((resolve,reject)=>{
let randomNum = parseInt(Math.random()*6+1);
console.log(randomNum);
if(randomNum>3){
resolve('买');
}
else{
reject('不买');
}
})
}
Promise.all([fn(),fn()]).then((x)=>{console.log(x,'success')},(y)=>{console.log(y,'error');});
- Promise.all 里面参数为一个数组,数组的每一项是一个返回promise 的函数调用
- then 的第一个参数是所有promise都成功的调用,返回结果是一个数组,数组的每一项为函数promise 的返回结果。
- then 的第二个参数:返回结果有一个失败则执行失败的回调,拿到的是第一个失败的值
2. 使用await
await 是可以获得多个promise 返回结果的,Promise.all()返回的也是promise结果。所以想要使用await 拿到多个promise的返回值,可以直接await Promise.all();
function fn(){
return new Promise((resolve,reject)=>{
let randomNum = parseInt(Math.random()*6+1);
console.log(randomNum);
if(randomNum>3){
resolve('买');
}
else{
reject('不买');
}
})
}
async function test(){
try{
let res = await Promise.all([fn(),fn()]);
console.log(res,'success');
}
catch(error){
console.log(error,'error');
}
}
test();
- Promise.all([fn(),fn()]) 都返回resolve(); 才能够拿到成功的返回值
- Promise.all([fn(),fn()]) 有一个返回reject(), 则进入catch(error), 拿到失败的返回值
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
猜你喜欢
微软电脑管家2.0公测版体验
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
Gramm Angle field GAF time-series data into the image and applied to the fault diagnosis
子空间结构保持的多层极限学习机自编码器(ML-SELM-AE)
VMD结合ISSA优化LSSVM功率预测
数据库技巧:整理SQLServer非常实用的脚本
【C# - 爬虫】使用Selenium实现爬虫,获取近七天天气信息(包含完整代码)
SegNet——论文笔记
为什么不使用VS管理QT项目
Operating System Kernel
随机推荐
MySQL重置root密码
mysql锁机制
Online public account article content to audio file practical gadget
搭建redis哨兵
NelSon:一款新的适配matlab编程语法的编程工具
Interpretation of EfficientNet: Composite scaling method of neural network (based on tf-Kersa reproduction code)
格拉姆角场GAF将时序数据转换为图像并应用于故障诊断
子空间结构保持的多层极限学习机自编码器(ML-SELM-AE)
IDEA 控制台 中文乱码问题(如果网上教程都无法解决你的问题的话)
数据库技巧:整理SQLServer非常实用的脚本
目标检测中的IoU、GIoU、DIoU与CIoU
JVM工具之 JPS
如何用matlab做高精度计算?【第二辑】
DOM的12中节点类型,通过关系或方法获取DOM节点,渲染到浏览器页面的一些特效功能,获取DOM节点来改变属性,点击图片,切换为所点击的图片为背景图,页面上的表单验证,点击底部导航栏切换界面
系统流量预估、架构设计方案
基于时序模式注意力机制(TPA)的长短时记忆(LSTM)网络TPA-LSTM的多变量输入风电功率预测
为什么不使用VS管理QT项目
nacos 返回 403 unknown user 太他么坑了 源码解析
Computer knowledge: desktop computers should choose the brand and assembly, worthy of collection
微软电脑管家2.0公测版体验