我試圖逐個運行這些函數,它將執行第一個函數後移動到第二個,等等..現在它將同時呈現這兩個函數,它當有超過3000個功能時,會佔用如此多的內存。Node.js - 逐一執行函數
webshot('google.com', 'google.jpeg', options, function(err) {});
webshot('yahoo.com', 'yahoo.jpeg', options, function(err) {});
我試圖逐個運行這些函數,它將執行第一個函數後移動到第二個,等等..現在它將同時呈現這兩個函數,它當有超過3000個功能時,會佔用如此多的內存。Node.js - 逐一執行函數
webshot('google.com', 'google.jpeg', options, function(err) {});
webshot('yahoo.com', 'yahoo.jpeg', options, function(err) {});
最後一個參數被稱爲「回調」。它會在工作完成時被調用。所以,如果你想要做這一次一個,將呼叫前一個的下一個內回調:
webshot('google.com', 'google.jpeg', options, function(err) {
webshot('yahoo.com', 'yahoo.jpeg', options, function(err) {});
});
當然,如果你有一個這些一堆(你提到3000!),你不會像這樣嵌套它們。我可能會創建要傳遞他們參數數組,然後使用回調循環:
function process(list, callback) {
var index = 0;
doOne();
function doOne() {
var entry = list[index++];
webshot(entry.domain, entry.img, entry.options, function(err) {
// ...error handling, etc...
if (index < list.length) {
doOne();
} else {
callback();
}
});
}
}
var webshots = [
{domain: 'google.com', img: 'google.jpeg', options: options},
{domain: 'yahoo.com', img: 'yahoo.jpeg', options: options},
// ...
];
process(webshots, function() {
// All done
});
邊注:這將是一個有點吸塵器承諾。有許多庫可以承諾 - 如果是Node式的回調API(比如webshot的),你可能會考慮這樣做。
如果你這樣做,你能處理這樣的承諾:
var webshots = [
{domain: 'google.com', img: 'google.jpeg', options: options},
{domain: 'yahoo.com', img: 'yahoo.jpeg', options: options},
// ...
];
allDone = webshots.reduce(function(p, entry) {
return p.then(function() {
return promisifiedWebshot(entry.domain, entry.img, entry.options);
});
}, Promise.resolve());
allDone.then(function() {
// All done
})
.catch(function() {
// Handle error
});
謝謝你的工作就像魅力! – user97811
您可以使用控制流庫像async:
'use strict';
const async = require('async');
async.series([
(callback) => {
webshot('google.com', 'google.jpeg', options, callback);
},
(callback) => {
webshot('yahoo.com', 'yahoo.jpeg', options, callback);
}
], (error) => {
if(error) {
console.log('Error: ' + error);
}
});
還有水電費的功能就像map
,each
, eachOf
允許您直接遍歷url列表並應用於該調用:
'use strict';
const async = require('async'),
urls = [
{url: 'google.com', img: 'google.jpeg'},
{url: 'yahoo.com', img: 'yahoo.jpeg'}
];
async.map(urls, (url, callback) => {
webshot(url.url, url.img, options, callback);
//I presumed webshot call the callback like callback(error, result)
}, (error, webshots) => {
//If a error occured, async will skip there and error will be set
//Else, webshots will be a array of all the results
});
什麼是網頁截圖?你只是想要順序地運行它們還是有其他的東西在圖片中。 – Nivesh
可能是這個https://github.com/brenden/node-webshot – martinczerwi
它會採取谷歌,然後雅虎的縮略圖..現在是羚羊同時採取縮略圖。我想採取谷歌縮略圖,然後採取雅虎縮略圖..不是在同一時間 – user97811