私のコントローラの1つにメソッドがあります。コントローラの目的は、webshot packageを使用してURLの配列を出力することです。Node.jsとExpress.jsでこのコードを改善する方法コールバックhellを避ける
これは、問題のコードです:
router.post('/capture', function (req, res, next) {
//Check params remove
var json = JSON.parse(req.body.data);
var promise = new Promise(function (resolve, reject) {
var totalImages = Object.keys(json).length;
var arrayListUrlImages = new Array(totalImages);
var counter = 0;
var completeDir = dir + ''; //Directory URL
for (var value of json) {
var url = 'http://example.com/' + id + '/' + value.anotherValue;
var folder = completeDir + id + '/' + value.anotherValue + '.jpg';
//Options for capturing image
var options = {
renderDelay: 1000,
quality: 100,
phantomConfig:
{
'local-to-remote-url-access': 'true',
'ignore-ssl-errors': 'true'
}
};
var anotherValue = value.anotherValue;
(function (anotherValue) {
webshot(url, folder, options, function (err) {
// screenshot now saved
if (err === null) {
var urlImage = "http://example.com/images/" + id + "/" + anotherValue + ".jpg";
arrayListUrlImages.push(urlImage);
counter++;
console.log("Counter: " + counter);
if (counter === totalImages) {
resolve(arrayListUrlImages);
}
}
else {
reject(err);
}
});
})(anotherValue);
}
}).then(function (arrayImages) {
res.send(arrayImages);
}).catch(function (errorVale) {
res.send(null);
});
});
このコードは問題なく働いている...しかし、私はもっとうまくしたいと思います。どのくらい多くのURLをチェックする必要があるのかわかりません(これは重要な詳細なので、それぞれまたは同等のために行う必要があります)。
私は約async packageを読んでいます...このコードをasync.parallelのように移動すると良いでしょうか?自分のコードでyieldを使うことはできますか?
ありがとうございます!
この質問は否決された理由を私は知らない...コードの – chemitaxis