我为javascript世界带来了新的变化,我有一个像这样的简单方法
function foo(items) {
var result = []
// Assume under forEach statement take 2 sec per loop
items.forEach(function(item) {
setTimeout(function() {
result.push(item + 2)
}, 2000)
})
return result
}
console.log(foo([1,2,3,4]))
console.log("Done")
结果:
[]
Done
输出除外:
[ 3, 4, 5, 6 ]
Done
任何人都可以帮助我,或者解释一下javascript中的异步来解决这个问题。
答案 0 :(得分:1)
摆脱setTimeout
,它应该按预期工作:
function foo(items) {
var result = []
// Assume under forEach statement take 2 sec per loop
items.forEach(function(item) {
result.push(item+2)
})
return result
}
console.log(foo([1,2,3,4]))
console.log("Done")
返回[3, 4, 5, 6]
答案 1 :(得分:1)
尝试以下
function foo(items) {
var result = []
// Assume under forEach statement take 2 sec per loop
items.forEach(function(item) {
// Create a promise for each async function
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(item + 2); // resolve the async function
}, 2000);
});
result.push(promise); // push the promise into array
});
// Create one promise for all the promises and return
return Promise.all(result)
}
// Now, foo function returns a promise and then is called once the promise is resolved which contains the data
foo([1,2,3,4]).then((response) => console.log(response)).then(() => console.log("Done"));

由于setTimeout
是一个ansync函数,即它不按顺序执行,因此,正如预期的那样,输出是一个空数组(当返回数组时,没有执行setTimeout函数的回调)。您可以使用Promises来处理异步功能。
答案 2 :(得分:-1)
使用Array.map
推送元素:
function foo(items) {
var result = []
items.map(_=>result.push(_+2))
return result
}

function foo(items) { // start function
var result = [] // the result array
items.map(_=>result.push(_+2)) // map over array and for every element set it equal to that element + 2
return result; // return resultant array
} // end function
foo = items => items.map(_=>_+2)
console.log(foo([1,2,3,4,5]))