这真的是一个asynchronous“类似”的循环?

我试图更多地了解承诺和asynchronous编程。 我试图做一个asynchronous循环(是的, 我知道有很多的库来完成这个 ,但他们不教我如何工作)使用承诺。

比方说,我想迭代一个数组,并将一个函数应用到“每个tick”的一个元素,而我做一些其他的东西。 所以我做了这个“async for-loop-like”函数:

function asyncFor_(elements, worker, index) { return new Promise((resolve, reject) => { process.nextTick(()=>{ if (index < elements.length) { try { worker(elements[index]) resolve(asyncFor_(elements, worker, index+1)) } catch(e) { reject() } } else { resolve() } }) }) } 

并用此testing:

 function logEnd() { console.log('End') } function logErr(e) { console.log(e) //Received console.log('I dont like 3. GTFO.') } function logItem(item) { if (item === 3) { throw Error('3? GTFO.') } console.log(item) } console.log('Begin') asyncFor_([1,2,3,4,5], logItem, 0) .then(logEnd) .catch(logErr) asyncFor_([6,7,8,9], logItem, 0) .then(logEnd) .catch(logErr) console.log('Displayed after begin and before the rest') 

输出是:

 Begin 1 6 2 7 8 I don't like 3. GTFO 9 End (End from the second asyncFor_ call) 

我认为这工作正常。 但同时我也怀疑。 也许我误解了结果。 我错过了什么? 这是“asynchronous”的错觉还是真的asynchronous?

是的,这是好的,是的,它是真正的asynchronous(也可以通过你的输出日志从两个并发循环中得到certificate)。

然而,它看起来有点像Promise构造函数反模式 ,并避免了你可以大大简化你的代码:

 function nextTick() { return new Promise(resolve => { process.nextTick(resolve); }); } function asyncFor_(elements, worker, index) { return nextTick().then(() => { if (index < elements.length) { worker(elements[index]); return asyncFor_(elements, worker, index+1); } }); } 

把你的代码放在callback函数中,你可以免费获得try-catch。 总是在最低的水平promisify! 🙂