promise的用法
阿新 • • 發佈:2018-10-16
進入 out 參數 比較 並行執行 sync 也會 timeout 處理
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)
)
promise的用法