- let p = new Promise(function(resolve, reject)
- // 异步操作
- setTimeout(function(){
- // 成功的回调, reject 为失败的回调;
- resolve(data);
- },2000);
- })
- //then 第一个参数执行 resolve, 第二个参数执行 reject;
- p.then(res=>{
- console.log(res)
- }).catch(err=>{
- //catch 执行 reject 类似 then 的第二个参数, 如果执行 resolve 回调异常时也会进入;
- console.log(err)
- })
- // 并行执行多个异步
- Promise.all([Async_1,Async_2,Async_3]).then(res=>{
- //res 为一个数组接收多个异步的回调参数
- console.log(res)
- )
- // 比较执行多个异步 (应用场景: 异步请求超时后的处理等)
- Promise.race([Async_1,Async_2,Async_3]).then(res=>{
- //res 为先执行完的异步操作的回调
- console.log(res)
- )
来源: http://www.bubuko.com/infodetail-2810145.html