gpt4 book ai didi

javascript - 用 q 循环并返回值

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:41 25 4
gpt4 key购买 nike

我试图找到循环数组、对数组的每个元素执行操作并使用 Q 返回结果的最佳方法。

假设我有这个数组:

var q = require('q');
var arr = [1, '2', "3", "undefined", undefined];
var values = [];

q.fcall(
function(){
arr.forEach(d){
if (d){
values.push(1);
}
else{
values.push(0);
}
}
return values;
}
).then(
function(v){
v.forEach(d){
console.log(d);
}
});

最佳答案

如果您执行的操作不是异步的,您可以只使用常规 Array#map并解析映射的数组:

var operationFunction = function(d) {
return d ? 1 : 0;
};

q(arr.map(operationFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});

如果您的操作是 Node.js 风格的异步函数,您可以将源数组映射到 Promise 数组,然后等待它们解析:

var operationFunction = function(d, done) {
process.nextTick(function() {
done(null, d ? 1 : 0);
});
};

var wrapperFunction = function(d) {
return q.nfcall(operationFunction, d);
};

q.all(arr.map(wrapperFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});

或者,如果操作函数是异步的并且您可以编辑它,则可以使用延迟对象:

var operationFunction = function(d) {
var deferred = q.defer();
process.nextTick(function() {
deferred.resolve(d ? 1 : 0);
});
return deferred.promise;
};

q.all(arr.map(operationFunction)).then(function(v) {
v.forEach(function(d) {
console.log(d);
});
});

关于javascript - 用 q 循环并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40742312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com