我正在敲打墙头,弄清楚如何将异步写入文件的数据推送到数组中。同步写入数据(并检查项目是否是列表中的最后一项)需要花费太多时间,所以我决定让它运行异步。在做了一些研究后,似乎我可以使用回调
我宁愿不使用外部库来执行此操作,因为我非常确定回调或Promise应该可以做到这一点。谢谢!
//Iterate through list and make HTTP request to get data
dataDocument.map(function(item, index) {
request(item, function(err, res, html) {
if (err) throw err;
renderData(html, item);
});
});
//Renders data
function renderData(html, item) {
...some calculations here.
writeData(output, id, function() {
pushed(output);
});
};
//Writes the data on file
function writeData(output, id) {
fs.appendFile('./output.json', output);
//SHOULD I USE A CALLBACK HERE TO PUSH INTO AN ARRAY ONCE IT'S COMPLETE?
};
//NEED HELP HERE: Pushed the data into an array and eliminates last comma.
function pushed(data) {
var arr = [];
arr.push(data);
}
答案 0 :(得分:0)
凭借承诺,它看起来更清洁,更精简。宣传所有相关功能,并使用Promise.all
知道何时收集了所有数据:
// Promisify all the involved callback-based functions:
function promiseRequest(item) {
return new Promise(function (resolve, reject) {
request(item, function (err, res, html) {
if (err) {
reject(err);
} else {
resolve(html);
}
})
})
}
//Renders data
function promiseRenderData(html, item) {
//...some calculations here.
return promiseWriteData(output, id).then(function() {
return output;
});
};
//Writes the data on file
function promiseWriteData(output, id) {
return new Promise(function (resolve, reject) {
fs.appendFile('./output.json', output, function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
//Iterate through list and make HTTP request to get data
Promise.all(dataDocument.map(function(item, index) {
return promiseRequest(item).then(function(html) {
return promiseRenderData(html, item);
};
})).then(function(arr) {
// Do something with `arr` here
});