简体   繁体   English

Node.js foreach + Promise

[英]Node.js foreach + promise

I want to print arr=[1, 2, 3, 4] like below. 我想像下面一样打印arr=[1, 2, 3, 4]

1 101 2 102 3 103 4 104 1 101 2 102 3 103 4 104

but result is below. 但结果如下。

1 2 3 4 101 102 103 104 1 2 3 4 101 102 103 104

my code 我的代码

var arr = [1, 2, 3, 4];


var promises = [];
arr.forEach(function(elem){
    print(elem)
        .then(addAndPrint)
}
)

function print(elem){
    return new Promise(function(resolve, reject){
        console.log(elem);
        resolve(elem);
    });
}
function addAndPrint(elem){
    console.log(elem + 100);
}

How can I get result I want? 我如何获得想要的结果?

I'm not sure what constraints you're working with but the choice to use Promises could use some explanation. 我不确定您使用的约束是什么,但是选择使用Promises可以使用一些解释。 Because the easiest solution is probably to not use Promises. 因为最简单的解决方案可能是不使用Promises。 Promises are good for asynchronous operations, but everything here is synchronous. 承诺对于异步操作是有好处的,但是这里的一切都是同步的。

 var arr = [1, 2, 3, 4]; arr.forEach(function(elem){ print(elem) addAndPrint(elem); }); function print(elem){ console.log(elem); } function addAndPrint(elem){ console.log(elem + 100); } 

.then s execute asynchronously (similar to setTimeout(.., 0) ) (even if the promise resolves immediately), whereas the promise creation function in new Promise((res, rej) => { runs synchronously. So, if you create a bunch of promises synchronously , such as with forEach before the main thread ends, those promises' blocks will all run immediately before any of the then s are reached. .then s 异步执行(类似于setTimeout(.., 0) )(即使promise立即解决),而new Promise((res, rej) => {的promise创建函数则同步运行。因此,如果您创建一堆诺言同步进行 ,例如在主线程结束之前使用forEach ,这些诺言的块将到达所有then 之前立即运行。

Use await and either reduce or for..of to ensure the iterations run in serial , not in parallel: 使用await以及reducefor..of来确保迭代以串行方式而不是并行方式运行:

 var arr = [1, 2, 3, 4]; var promises = []; arr.reduce(async function(lastPromise, elem) { await lastPromise; return print(elem) .then(addAndPrint) }, Promise.resolve()) function print(elem) { return new Promise(function(resolve, reject) { console.log(elem); resolve(elem); }); } function addAndPrint(elem) { console.log(elem + 100); } 

.then只能保证你addAndPrint(1)方法后执行print(1)方法,但是无法进行print(2)addAndPrint(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM