
promise與 fetch、async/await_fetch async 獲取結(jié)束標志-CSDN博客手寫promise A、catch、finally、all、allsettled、any、race-CSDN博客【建議星星】要就來45道Promise面試題一次爽到底(1.1w字用心整理) - 掘金目錄每隔1秒輸出1,2,3紅黃綠燈交替亮按序執(zhí)行數(shù)組異步加載圖片每隔1秒輸出1,2,3const arr [1, 2, 3] arr.reduce((p, x) { return p.then(() { return new Promise(r { setTimeout(() r(console.log(x)), 1000) }) }) }, Promise.resolve())紅黃綠燈交替亮function red() { console.log(red); } function green() { console.log(green); } function yellow() { console.log(yellow); } const light function (timer, cb) { return new Promise(resolve { setTimeout(() { cb() resolve() }, timer) }) } const step function () { Promise.resolve().then(() { return light(3000, red) }).then(() { return light(2000, green) }).then(() { return light(1000, yellow) }).then(() { return step() }) } step();按序執(zhí)行數(shù)組const time (timer) { return new Promise(resolve { setTimeout(() { resolve() }, timer) }) } const ajax1 () time(2000).then(() { console.log(1); return 1 }) const ajax2 () time(1000).then(() { console.log(2); return 2 }) const ajax3 () time(1000).then(() { console.log(3); return 3 }) function mergePromise (ajaxArray) { // 存放每個ajax的結(jié)果 const data []; let promise Promise.resolve(); ajaxArray.forEach(ajax { // 第一次的then為了用來調(diào)用ajax // 第二次的then是為了獲取ajax的結(jié)果 promise promise.then(ajax).then(res { data.push(res); return data; // 把每次的結(jié)果返回 }) }) // 最后得到的promise它的值就是data return promise; } mergePromise([ajax1, ajax2, ajax3]).then(data { console.log(done); console.log(data); // data 為 [1, 2, 3] }); // 要求分別輸出 // 1 // 2 // 3 // done // [1, 2, 3]異步加載圖片function loadImg(url) { return new Promise((resolve, reject) { const img new Image(); img.onload function() { console.log(一張圖片加載完成); resolve(img); }; img.onerror function() { reject(new Error(Could not load image at url)); }; img.src url; });