DIEA
2019-07-26 15:14:08
等待多個(gè)并行操作如何更改以下代碼,以便觸發(fā)兩個(gè)異步操作并使其有機(jī)會(huì)并發(fā)運(yùn)行?const value1 = await getValue1Async();const value2 = await getValue2Async();// use both values我需要這樣做嗎?const p1 = getValue1Async();const p2 = getValue2Async();const value1 = await p1;const value2 = await p2;// use both values
3 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
const [value1, value2] = await Promise.all([getValue1Async(),getValue2Async()]);
const promise1 = async() => { return 3;}const promise2 = async() => { return 42;}const promise3 = async() => { return 500; // emulate an error // throw "something went wrong...";}const f1 = async() => { try { // returns an array of values const results = await Promise.all([promise1(), promise2(), promise3()]); console.log(results); console.log(results[0]); console.log(results[1]); console.log(results[2]); // assigns values to individual variables through 'array destructuring' const [value1, value2, value3] = await Promise.all([promise1(), promise2(), promise3()]); console.log(value1); console.log(value2); console.log(value3); } catch (err) { console.log("there was an error: " + err); }}f1();

慕仙森
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用.catch()和Promise.all()
unhandled rejection
Promise.all()
let myTimeout = (ms, is_ok) => new Promise((resolve, reject) => setTimeout(_=> is_ok ? resolve(`ok in ${ms}`) : reject(`error in ${ms}`), ms));let handleRejection = promise => promise .then((...r) => [null, ...r]) .catch(e => [e]); (async _=> { let res = await Promise.all([ myTimeout(100, true), myTimeout(200, false), myTimeout(300, true), myTimeout(400, false) ].map(handleRejection)); console.log(res);})();
let myTimeout = (ms, is_ok) => new Promise((resolve, reject) => setTimeout(_=> is_ok ? resolve(`ok in ${ms}`) : reject(`error in ${ms}`), ms));let has_thrown = false;let handleRejection = promise => promise .then((...r) => [null, ...r]) .catch(e => { if (has_thrown) { console.log('not throwing', e); } else { has_thrown = 1; throw e; } });(async _=> { try { let res = await Promise.all([ myTimeout(100, true), myTimeout(200, false), myTimeout(300, true), myTimeout(400, false) ].map(handleRejection)); console.log(res); } catch(e) { console.log(e); } console.log('we are done');})();
添加回答
舉報(bào)
0/150
提交
取消