我在 node.js 中有一个批处理作业: 将文件复制到目录中,对文件进行分析,然后删除文件。
我想遍历一组作业并使用生成器暂停执行,直到该批处理作业完成,然后再开始另一个作业。这是我目前所拥有的:
const cars = ["toyota", "honda", "acura"];
function copyFilesAndRunAnalysis(car) {
return new Promise(function(resolve, reject) {
setTimeout(function() { // simulate some delay
resolve(); // control should return to generator here
}, 1000);
});
}
function* doCar(car) {
yield copyFilesAndRunAnalysis(car);
}
// BEGIN HERE
console.log('start here');
carBatch = doCar(cars[0]);
carBatch.next(); // confusion here!!!
carBatch.next(); // should this all be in a forEach loop?
我想做的是让 forEach 循环遍历每辆车,在 copyFilesAndRunAnalysis
方法中完成所有相应的工作——暂停直到 Promise.resolve()
然后继续下一个。尝试 forEach 根本无法运行任何东西。
最佳答案
您不在问题的 js
处使用 .value
。 Generator
生成的 next()
对象的 .value
将是 copyFilesAndRunAnalysis 返回的
,其中 Promise
.then()
可以链接到 .next().value()
,Array.prototype.shift()
可用于递归调用 doCar
直到没有项目保留在 cars
数组的原始或副本中。
const cars = ["toyota", "honda", "acura"];
let carsCopy = cars.slice(0);
function copyFilesAndRunAnalysis(car) {
return new Promise(function(resolve, reject) {
setTimeout(function() { // simulate some delay
resolve(car); // control should return to generator here
}, 1000);
})
}
function* doCar(cars) {
yield copyFilesAndRunAnalysis(cars);
}
// BEGIN HERE
console.log("start here");
carBatch = doCar(carsCopy.shift());
carBatch.next().value.then(function re(data) {
console.log(data);
return carsCopy.length
? doCar(carsCopy.shift()).next().value.then(re)
: "complete"
})
.then(function(complete) {
console.log(complete);
})
注意,同样的过程可以利用Promise
,递归来实现;不使用 Generator
函数。
const cars = ["toyota", "honda", "acura"];
let carsCopy = cars.slice(0);
function copyFilesAndRunAnalysis(car) {
return new Promise(function(resolve, reject) {
setTimeout(function() { // simulate some delay
resolve(car); // control should return to generator here
}, 1000);
})
}
// BEGIN HERE
console.log("start here");
carBatch = copyFilesAndRunAnalysis(carsCopy.shift());
carBatch.then(function re(data) {
console.log(data);
return carsCopy.length
? copyFilesAndRunAnalysis(carsCopy.shift()).then(re)
: "complete"
})
// do stuff when all items within `cars` have been
// processed through `copyFilesAndRunAnalysis`
.then(function(complete) {
console.log(complete);
})
关于javascript - 使用生成器暂停直到 promise 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366839/