![](/img/trans.png)
[英]Iterating through Object data returned asynchronously through Promise in Angular?
[英]Asynchronously write data to GCS inside of a Promise
我正在嘗試找到一種方法將 json 數據寫入 promise 內部的 Google Cloud Storage 存儲桶中的文件。
我發現,如果我嘗試將 and.push() 值一個一個地放入一個數組然后返回它,它只會給我來自數組的前 3 個結果(而 console.log 將返回所有內容)。
如果我嘗試在本地 scope 中寫一些東西,它只會返回數組中的最后一個值(並覆蓋所有以前的值而不是附加它們)。
所以基本上我的問題是:有沒有辦法編寫一個 promise 或類似的方法來等待收集所有循環的值,一旦完成,將這些值返回給 function,然后將其全部上傳到 GCS?
或者有沒有一種方法可以在抓取數據的同時將這些值異步寫入 GCS 中的 .json 文件?
const urls = [/* 20+ URLs go here... */];
let promises = [];
// Build array of Promises
urls.map(function(url) {
promises.push(axios.get(url));
});
// Map through the array of promises and get the response results
axios.all(promises).then((results) => {
results.map((res) => {
try {
// Scrape the data
const $ = new JSDOM(res.data);
const data = {};
data.title = ($.window.document.querySelector('head > title') !== null ? $.window.document.querySelector('head > title').text : '');
data.description = ($.window.document.querySelector("meta[name='description']") !== null ? $.window.document.querySelector('meta[name="description"]').content : '');
data.robots = ($.window.document.querySelector("meta[name='robots']") !== null ? $.window.document.querySelector("meta[name='robots']").content : '');
const value = JSON.stringify(data) + '\n';
// Tried array.push(value) here but doesn't return all the values?
// Any way to return all the values and then bulk upload them to GCS outside of this code block?
const file = storage.bucket(bucketName).file(filename);
file.save(value, function(err) {
if (!err) {
// file written
}
})
} catch(e) {
console.log(e);
}
})
})
抱歉解釋不好,基本上我不能將所有值推送到數組然后上傳,如果我嘗試一個一個上傳值,我只能得到循環數組中的最后一個值。
注意:我沒有嘗試使用 fs.writeFile() 將數據保存到本地的 a.json 文件,然后上傳到 GCS,而是將 JSON 數據直接發送到 GCS,而無需中間的步驟。
如果我正確理解你需要什么它應該工作
axios.all(promises).then((results) => {
const uploads = results.map((res) => {
try {
// Scrape the data
const $ = new JSDOM(res.data);
const data = {};
data.title = ($.window.document.querySelector('head > title') !== null ? $.window.document.querySelector('head > title').text : '');
data.description = ($.window.document.querySelector("meta[name='description']") !== null ? $.window.document.querySelector('meta[name="description"]').content : '');
data.robots = ($.window.document.querySelector("meta[name='robots']") !== null ? $.window.document.querySelector("meta[name='robots']").content : '');
const value = JSON.stringify(data) + '\n';
return new Promise((resolve, reject) => {
const file = storage.bucket(bucketName).file(filename);
file.save(value, function(err) {
if (!err) {
resolve()
}
reject()
})
});
} catch(e) {
console.log(e);
}
})
return Promise.all(uploads);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.