我有一個NodeJS腳本爲用戶調用API,爲每個用戶獲取多個數據並將其全部寫入本地文件。我試圖在將所有數據寫入文件後將該文件上傳到服務器。問題在於應該上傳文件的代碼在文件完全填充之前執行。代碼寫在下面。我無法弄清楚如何保證等待第一個功能的完成。NodeJS承諾等待完成
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);
}
})
})
任何幫助,將不勝感激。
'javascript'的哪個部分應該最後調用? 'writer.write()'有回調,還是返回'Promise'? – guest271314
@ guest271314最後一個功能需要將文件上傳到服務器,並且需要最後調用 – alminh
[您無法在承諾中使用'.forEach'](http://stackoverflow.com/q/37576685/1048572)。 – Bergi