我正在做一个简单的任务,我有一个正方形和矩形等形状的数组,还有另一个数组的大小作为参数传递给名为findAllObjectArea
的函数。
我想从我的函数findAllObjectArea
返回一个诺言,该诺言表示我所有对象的区域数组。同样在我的函数中,findObjectArea
我想返回表示该区域的promise。
我已经创建了下面的模板,但是我正在努力寻找它的正确语法。您能帮我吗?
let findObjectArea = (myobject, sizes) => {
new Promise(function(resolve, reject) {
if(myobject== 'square') {
resolve(sizes[0]*sizes[0]);
} else if(myobject== 'rectangle') {
resolve(sizes[0]*sizes[1]);
}
}
}
let findAllObjectArea = (objects, all_sizes) => {
new Promise((resolve, reject) => {
for(var i=0; i<objects.length; i++) {
findObjectArea (objects[i], all_sizes[i]);
}
);
}
答案 0 :(得分:1)
重写第二个功能:
// Use `const`, you're never gonna change this.
const findAllObjectArea = (objects, all_sizes) => {
const promises = [];
// I'm using 'let'. Why use 'var' if you have access to 'let' ;)
for(let i=0; i < objects.length; i++) {
promises.push(findObjectArea (objects[i], all_sizes[i]));
}
// Now we wait for ALL promises to resolve
return Promise.all(promises);
}
从您的问题中并不清楚要对所有这些操作的结果执行什么操作,所以我假设您要返回一个包含所有结果的数组。
只是为了好玩,这是具有更现代的循环原语的另一种选择:
// Use `const`, you're never gonna change this.
const findAllObjectArea = (objects, all_sizes) => {
const promises = [];
// I'm using 'let'. Why use 'var' if you have access to 'let' ;)
for(const [index, obj] of objects.entries()) {
promises.push(findObjectArea (obj, all_sizes[index]));
}
// Now we wait for ALL promises to resolve
return Promise.all(promises);
}