1 回答

TA貢獻1842條經(jīng)驗 獲得超21個贊
resolve(areas_array)將把承諾解析為一個空數(shù)組,因為還沒有then執(zhí)行任何回調(diào)。
所以首先生成一個 promise 數(shù)組(每一個都是通過調(diào)用 獲得的calculateArea),然后調(diào)用Promise.all:
let getAreas = (shapes, values_arr) => {
return Promise.all(shapes.map((shape, i) => calculateArea(shape, values_arr[i])))
.catch(() => [-1]);
}
您應(yīng)該在這個級別下決心[-1],而不是在calculateArea. 在那里你可以使用reject()和傳遞你喜歡的任何東西。它沒有被使用。
旁注:當(dāng)你有一個(或多個)承諾時,就像你從調(diào)用中得到的一樣calculateArea,沒有必要創(chuàng)建另一個new Promise依賴于這些承諾的承諾。這樣做是一種反模式
演示:
let calculateArea = (shape, values) => {
return new Promise((resolve, reject) => {
switch(shape) {
case 'square':
resolve(values[0]*values[0]);
break;
case 'rectangle':
resolve(values[0] * values[1]);
break;
case 'circle':
resolve(values[0]*values[0] * 3.14);
break;
case 'triangle':
resolve(0.5 * values[0]*values[1]);
break;
default:
reject();
}
});
}
// Complete the generateArea function below.
// It returns a Promise which on success,
// resolves to an array of areas of all the shapes and on failure, resolves to [-1].
let getAreas = (shapes, values_arr) => {
return Promise.all(shapes.map((shape, i) => calculateArea(shape, values_arr[i])))
.catch(() => [-1]);
}
getAreas(['square', 'circle'], [[10], [5]]).then(console.log);
還有一個注意術(shù)語:我更改了代碼中的注釋,因為說Promise 在成功時返回某些內(nèi)容是一種誤導(dǎo):promise 不是函數(shù),因此它不返回任何內(nèi)容。你可以說它解決了某些事情。
添加回答
舉報