return 使用 q 库在 nodejs 中通过 promise 的值
return the value via promise in nodejs using q library
var a = [0,1,2,3];
如何将 getVal 的值传递给 prod 和 tst。
function startFunc(){
var deferred = Q.resolve();
var a = [0,1,2,3];
a.forEach(function (num, i) {
var getVal = num;
deferred = deferred
.then(function(num){
var def = Q.defer();
console.log("\n\niteration:"+i + " a: "+getVal);
return def.resolve(getVal);
}).then(prod)
.then(tst)
.then(compare)
.catch(function(error){
console.log(error);
});
});
return deferred.promise;
}
这里是一个nodejsfiddlelink。转到 link 并执行按 shift+enter 执行。
https://tonicdev.com/pratikgala/5637ca07a6dfbf0c0043d7f9
执行此操作时,我想将 getVal 的值作为承诺传递给 prod。
我该怎么做。当我 运行 以下函数时,getVal 不会返回到 prod。
您可以显着简化循环,停止使用延迟反模式并像这样将 val 传递给 prod()
:
function startFunc() {
var a = [0, 1, 2, 3];
return a.reduce(function(p, val, i) {
return p.then(function() {
return prod(val);
}).then(test).then(compare).catch(function (error) {
console.log(error);
});
}, Q());
}
startFunc().then(function(finalVal) {
// completed successfully here
}, function(err) {
// error here
});
这旨在遍历数组中的项目,将每个项目传递给 prod()
并传递给 运行 数组中每个项目的承诺链,一个接一个,以便数组中第一项的整个承诺链在数组中的下一项开始处理之前完成。最终值将是一个承诺,它解析为 .reduce()
循环 return 中的最后一步。如果您希望累积 return 个值的数组,也可以这样做。
仅供参考,您可以阅读有关避免延迟反模式的内容 here。
var a = [0,1,2,3];
如何将 getVal 的值传递给 prod 和 tst。
function startFunc(){
var deferred = Q.resolve();
var a = [0,1,2,3];
a.forEach(function (num, i) {
var getVal = num;
deferred = deferred
.then(function(num){
var def = Q.defer();
console.log("\n\niteration:"+i + " a: "+getVal);
return def.resolve(getVal);
}).then(prod)
.then(tst)
.then(compare)
.catch(function(error){
console.log(error);
});
});
return deferred.promise;
}
这里是一个nodejsfiddlelink。转到 link 并执行按 shift+enter 执行。 https://tonicdev.com/pratikgala/5637ca07a6dfbf0c0043d7f9
执行此操作时,我想将 getVal 的值作为承诺传递给 prod。
我该怎么做。当我 运行 以下函数时,getVal 不会返回到 prod。
您可以显着简化循环,停止使用延迟反模式并像这样将 val 传递给 prod()
:
function startFunc() {
var a = [0, 1, 2, 3];
return a.reduce(function(p, val, i) {
return p.then(function() {
return prod(val);
}).then(test).then(compare).catch(function (error) {
console.log(error);
});
}, Q());
}
startFunc().then(function(finalVal) {
// completed successfully here
}, function(err) {
// error here
});
这旨在遍历数组中的项目,将每个项目传递给 prod()
并传递给 运行 数组中每个项目的承诺链,一个接一个,以便数组中第一项的整个承诺链在数组中的下一项开始处理之前完成。最终值将是一个承诺,它解析为 .reduce()
循环 return 中的最后一步。如果您希望累积 return 个值的数组,也可以这样做。
仅供参考,您可以阅读有关避免延迟反模式的内容 here。