我是nodejs中的新手,所以我有一个简单的问题,但无法解决它。
例如,我有这样的函数:
var func = function(){
setTimeout(function(){
return 5;
}, 1000);
};
当我打电话给func时,我得到'未定义'。我理解为什么,但是我无法理解如何改变我的函数来返回5而不是undefined
我可以用callback参数重写func,并从setTimeout调用callback,但是我想在不使用回调的情况下从函数返回结果。
在V8中我们有生成器和关键字'yield',我认为它可能对我有帮助,所以任何人都可以解释它是如何工作的以及如何在这个例子中使用它。感谢。
答案 0 :(得分:1)
好的,这是我对你的问题陈述的理解(你应该首先把它放在你的问题中)。
您有一个对象实例的数组,该实例具有异步方法,最终会产生一些值。而且,您希望调用数组中的每个对象并生成一个异步结果数组。
有几种方法可以解决这个问题。我将首先向Promises展示一个。
// your object
function MyObj() {
}
// with an async method that returns a promise
MyObj.prototype.doAsync = function() {
return new Promise(function(resolve) {
setTimeout(function() {
// create some value to resolve with here
// I've just substituted a random value
resolve(Math.floor(Math.random() * 1000));
}, 50);
});
}
// make an array of these objects like your problem statement described
var arr = [];
for (var i = 0; i < 20; i++) {
arr[i] = new MyObj();
}
// collect an array of promises by running all the async methods
var promises = [];
for (i = 0; i < arr.length; i++) {
promises.push(arr[i].doAsync());
}
// wait for all the promises to be done
Promise.all(promises).then(function(results) {
// array of async results here
log(results);
});
function log(x) {
var div = document.createElement("div");
div.innerHTML = JSON.stringify(x);
document.body.appendChild(div);
}
&#13;
有关从异步函数返回数据的一般参考,请参阅How do I return the response from an asynchronous call?