我有一个NodeJS脚本,为用户调用API,为每个用户获取多个数据并将其全部写入本地文件。我将所有数据写入文件后尝试将该文件上传到服务器。问题是应该在文件完全填充之前执行应该上载文件的代码。代码如下。我无法弄清楚如何做出承诺等待第一个功能完成。
var fs = require('fs');
var server = require('some-server');
var service = require('./some-service.js');
var moment = require('moment-timezone');
var csvWriter = require('csv-write-stream');
var writer = csvWriter({
sendHeaders: false
});
var users = require('./some-users')
writer.pipe(fs.createWriteStream('myFile' + '.txt'))
service.login().then(function (response) {
users.forEach(function (user) {
service.getSpecificUser(user).then(function (response) {
var myUser = JSON.parse(response)
service.getDataForUser(user.Info).then(function (response) {
var userData = JSON.parse(response);
if (userData.IsValid) {
userData.AdditionalInfo.forEach(function (additionalInfo) {
service.getAdditionalInfo(myUser.Info, userData.data).then(function (response) {
//Collect additional info and combine final results to write into file
// write to output csv file
writer.write({
//write information that is of interest
})
}, function (error) {
console.log('error getting additional data', error);
})
}
)
}
}, function (error) {
console.log('error getting user data', error)
})
}, function (error) {
console.log('error', myUser, error)
})
});
}, function (error) {
console.log('not logged', response);
}).then(function () {
//perform uploading to server
var fpath = 'path of file that contains downloaded data'
console.log("Trying to upload to file: " +fpath)
service.UploadFile(fpath, function (error, result, response) {
if (!error) {
console.log("Uploaded " + name);
}
else {
console.log(error);
}
})
})
任何帮助都将不胜感激。
答案 0 :(得分:1)
您可以将Promise.all()
,Array.prototytpe.map()
替换为.forEach()
。 csv-write-steam
的文档似乎使用.end()
在.write()
完成了致电.then()
。
service.login().then(function(response) {
return Promise.all(users.map(function(user) {
return service.getSpecificUser(user).then(function(response) {
var myUser = JSON.parse(response)
return service.getDataForUser(user.Info).then(function(response) {
var userData = JSON.parse(response);
if (userData.IsValid) {
return Promise.all(userData.AdditionalInfo.map(function(additionalInfo) {
return service.getAdditionalInfo(myUser.Info, userData.data).then(function(response) {
//Collect additional info and combine final results to write into file
// write to output csv file
writer.write({
//write information that is of interest
});
})
}))
}
})
})
}));
})
.then(function() {
writer.end();
//perform uploading to server
var fpath = 'path of file that contains downloaded data'
console.log("Trying to upload to file: " + fpath)
service.UploadFile(fpath, function(error, result, response) {
if (!error) {
console.log("Uploaded " + name);
} else {
console.log(error);
}
})
})
.catch(function(e) {
console.log(e)
})