Prepending to a file in javascript using OS.File - javascript

Any idea why onSuccess is never called?
filesystem ..
rob#work:~$ cat test.txt
hello
hello2
rob#work:~$ pwd
/home/rob
addon code ..
var filePath = '/home/rob/test.txt',
combinedString = 'new file content';
const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
OS.File.read(filePath).then(function(data) { // check if specified file exists
console.log(data)
function onSuccess(array) { // prepend to file
let text = new TextDecoder().decode(array);
let encodedArray = new TextEncoder().encode(combinedString + text);
console.log('exists: ' + combinedString + text);
var promise = OS.File.writeAtomic(filePath, encodedArray);
promise.then(
function() {
console.log('success');
},
function(ex) {
console.log('fail');
}
);
}
}, function(ex) { // file doesn't exist, create a new one
if (ex.becauseNoSuchFile) {
let encodedArray = new TextEncoder().encode(combinedString);
var promise = OS.File.writeAtomic(filePath, encodedArray);
console.log('new: ' + combinedString + text);
promise.then(
function() {
console.log('success');
},
function(ex) {
console.log('fail');
}
);
}
});
this is the only output in console ..
console.log: savetexttofile: Uint8Array {"0":104,"1":101,"2":108,"3":108,"4":111,"5":10,"6":104,"7":101,"8":108,"9":108,"10":111,"11":50,"12":10}
Total time: 5.596181 seconds
Program terminated successfully.

let promise = OS.File.read(filePath);
promise = promise.then(function onSuccess(contents) {
let text = new TextDecoder().decode(contents);
combinedString = combinedString + '\n\n' + text;
if (System.getPlatform().indexOf('win') >= 0)
combinedString = combinedString.replace(/[\n]/g, '\r\n');
let encodedArray = new TextEncoder().encode(combinedString);
var promise = OS.File.writeAtomic(filePath, encodedArray);
promise.then(
function() {
console.log('success');
},
function(ex) {
console.log('error');
}
);
return true;
},
function onError(reason) {
if (System.getPlatform().indexOf('win') >= 0)
combinedString = combinedString.replace(/[\n]/g, '\r\n');
let encodedArray = new TextEncoder().encode(combinedString);
if (reason.becauseNoSuchFile()) {
var promise = OS.File.writeAtomic(filePath, encodedArray);
promise.then(
function() {
console.log('success');
},
function(ex) {
console.log('error');
}
);
return false;
}
});

Related

Order of Promise Resolution Not As Expected in Promise-Containing For-Loop

I need to perform a rather complicated chain of promise resolutions to get and save data that is located in PDFs that are uploaded by a user. Everything works fine for single PDFs, but it breaks as soon as I try to upload multiple PDFs because the order in which the resolution proceeds isn't as I expect.
I call the function saveDoc on each file in an array:
saveDoc: function(){
var files = this.$refs.upload.uploadFiles
var self=this;
var promises = []
for (var i=0; i<files.length; i++){
(function(){
var file = files[i]
var name = file['name']
if (!(/\.pdf/i.test(name))){
name+='.pdf'
}
var type = mime.lookup(name)
var file = file['raw'];
var beforeUrl = self.selectedCategories.join('&&&')
console.log('going to save: ' + name) // Because of the IIFE, I'm not expecting this to log only after all steps 1 - 20 have been completed for each file
Store.getFileData(file).then(function(data){
console.log(2)
return Store.saveDoc(name, type, data, beforeUrl).then(url => {
console.log(8)
return Text.getText(url).then(text => {
console.log(12)
return Text.getMetadata(text, url).then(metadata => {
console.log(20)
if (metadata.length){
return Store.saveMetadata(beforeUrl, metadata, name)
}
return Store.createCategory(name, self.selectedCategories, '')
})
})
})
})
})()
}
},
I'm sure the promises could use some work, but what seems to be the problem is that the line console.log('going to save: ' + name) is called twice before the entire sequence 1-20 is carried out for one file (see error message of number sequence at bottom of this post). I tried to prevent this using an IIFE, but I guess I didn't do this right.
store.js
getData: function(url){
return new Promise(function(accept, reject){
console.log(4)
documentation.get(url, function(err, body) {
console.log(5)
if (!err){
console.log(body);
accept(body)
}
});
})
},
getFileData: function(file){
var reader = new FileReader();
return new Promise(function(accept, reject){
console.log(1)
reader.onload = (e) => {
// var data = e.target.result.replace(/^data:[A-Za-z]+\/[A-Za-z]+;base64,/, '')
// console.log('base 64: ' + data)
var res = new Uint8Array(e.target.result)
accept(res)
};
reader.readAsArrayBuffer(file);
})
},
saveDoc: function(name, type, filedata, url){
console.log(3)
var self=this
return new Promise(function(accept, reject){
return self.getData(url).then(data => {
console.log(6)
var rev = data['_rev']
return documentation.attachment.insert(url, name, filedata, type,
{ rev: rev }, function(err, body) {
if (!err){
console.log(7)
var fullUrl = 'http://dev04/documentation/'+url+'/'+name
accept(fullUrl)
}
else {
console.log(err)
}
})
}).catch(err => {
console.log(err)
})
})
},
saveMetadata: function(url, metadata, name){
var fileName = path.basename(name)
var self=this
return new Promise(function(accept, reject){
self.getData(url).then(data => {
var meta
var rev = data['_rev']
if(!data['metadata']){
data['metadata'] = {}
}
data['metadata'][fileName] = metadata
var datastring = JSON.stringify(data)
documentation.insert(data, url, function(err, body, header) {
if (err) {
console.log(err.message);
return;
}
});
}).catch(err => {
console.log(err)
})
})
},
text.js
export default {
getText: function(url){
console.log(9)
var result = []
return new Promise(function(accept, reject){
console.log(10)
return pdfjs.getDocument(url).then(pdf => {
console.log(11)
var pdf = pdfjs.getDocument(url);
return pdf.then(function(pdf) { // get all pages text
var maxPages = pdf.pdfInfo.numPages;
var countPromises = []; // collecting all page promises
for (var j = 1; j <= maxPages; j++) {
var page = pdf.getPage(j);
var txt = "";
countPromises.push(page.then(function(page) { // add page promise
var textContent = page.getTextContent();
// console.log('the content is ' + textContent)
return textContent.then(function(text){ // return content promise
var val = text.items.map(function (s) { return s.str; }).join('&&&')+'&&&'; // value page text
result.push(val)
// console.log(val + ' should be one page of text')
return val
});
}));
}
// Wait for all pages and join text
return Promise.all(countPromises).then(function (texts) {
accept(texts.join(''))
});
});
});
})
},
getMetadata: function(text, url){
console.log(13)
var result = []
var self = this
return new Promise(function(accept, reject){
self.getpageno(url).then(function(pagecount){
console.log(19)
try {
var dataMatch = rx.exec(text)
var produktDaten = dataMatch[1].split("&&&").filter(Boolean);
console.log(produktDaten)
var dokuArr = dataMatch[2].split("&&&").filter(Boolean);
for (var i=0; i<produktDaten.length; i+=4){
var entry = {}
entry.pagecount = pagecount
entry.kks = {}
entry.kks.pages = {}
var kksNummer = produktDaten[i];
entry.kks.nummer = kksNummer;
for(var j=0; j<dokuArr.length; j+=3){
var nummer = dokuArr[j];
var beschreibung = dokuArr[j+1];
var seite = dokuArr[j+2];
// make sure seite is a digit
if (!(/^\d+$/.test(seite))){
console.log(seite + ' was not a valid page number')
throw err
}
if (/(A|a)lle?/i.test(nummer)){
entry.kks.pages[beschreibung] = seite;
// self.tableEntry.kks.url = url;
// self.tableEntry.fileName = name;
///// kksNummern.forEach(function(kks){
// self.tableEntry.kks;
// })
}
else if (nummer === kksNummer) {
entry.kks.pages[beschreibung] = seite;
// entry.kks.url = url;
// entry.fileName = name
}
}
entry.hersteller = produktDaten[i+1]
entry.typ = produktDaten[i+2]
entry.artikelNummer = produktDaten[i+3]
result.push(entry)
}
}
catch(e){
return accept(result)
}
return accept(result)
/* if (result.length>0){
console.log('accepting the result')
}
reject()*/
}).catch(err => {
console.log(err)
})
})
},
getpageno: function(url){
console.log(14)
var self=this
var pdf = pdfjs.getDocument(url);
return pdf.then(function(pdf){
console.log(15)
var maxPages = pdf.pdfInfo.numPages;
var countPromises = []; // collecting all page promises
for (var j = 1; j <= maxPages; j++) {
try {
var page = pdf.getPage(j);
var txt = "";
countPromises.push(page.then(function(page) { // add page promise
var textContent = page.getTextContent();
return textContent.then(function(text){ // return content promise
console.log(16)
return text.items.map(function (s) { return s.str; }).join('&&&'); // value page text
});
}));
}
catch(e){
console.log(e)
}
}
// Wait for all pages and join text
return Promise.all(countPromises).then(function (texts) {
// since doumentation pages do not add the final '&&&', must add one manually (only after rx has been found)
console.log(17)
var fulltext = texts.reduce(function(full, text){
if (rx.test(full)){
var next = '&&&'+text
return full+=next
}
return full+=text
}, '')
return [fulltext, texts]
});
}).then(function(textarr){
console.log(18)
var fulltext = textarr[0]
self.fulltext = fulltext;
var texts = textarr[1]
try {
var partialmatch = rx.exec(fulltext)[0]
var count = texts.reduce(function(pageno, text){
var tomatch = text.replace(/.*Typ&&&/, '')
if (tomatch.length>0 && partialmatch.indexOf(tomatch) > -1){
pageno++
}
return pageno;
}, 0)
}
catch(e){
console.log(e)
}
return count;
}).catch(err => {console.log(err)})
}
}
I use the console to log the order I am expecting for the functions. I am expecting the numbers 1 - 20 in order, but I get the following.
going to save: 03_.pdf selector.js:211:6
1 store.js:227:4
going to save: 2017.07.05_0016 E161206.pdf selector.js:211:6
1 store.js:227:4
2 selector.js:213:7
3 store.js:239:3
4 store.js:213:4
2 selector.js:213:7
3 store.js:239:3
4 store.js:213:4
5 store.js:215:5
Object { _id: "Test", _rev: "36-85a08c0852ccab78c0b4c10369e83fb2", rank: 7, icon: "wrench", metadata: Object, _attachments: Object } store.js:217:6
6 store.js:243:5
5 store.js:215:5
Object { _id: "Test", _rev: "36-85a08c0852ccab78c0b4c10369e83fb2", rank: 7, icon: "wrench", metadata: Object, _attachments: Object } store.js:217:6
6 store.js:243:5
7 store.js:247:7
8 selector.js:215:8
9 text.js:12:3
10
11 text.js:17:5
12 selector.js:217:9
13 text.js:50:3
14 text.js:112:3
15 text.js:116:4
16 text.js:129:8
17 text.js:142:5
18 text.js:153:4
19 text.js:57:5
20
Can anyone offer any advice on how to get this order correct? Thank you.

why isn't this promise resolving?

I have a promise that is meant to collect metadata on a file and then resolve it with the metadata that was collected. Here is how I am trying to get its result:
getMetadata: function(text, url){
return this.getpageno(url).then(function(pagecount){
return new Promise(function(accept, reject){
var result = []
var dataMatch = rx.exec(text)
var produktDaten = dataMatch[1].split("&&&").filter(Boolean);
var dokuArr = dataMatch[2].split("&&&").filter(Boolean);
console.log('the produktdaten are ' + produktDaten)
for (var i=0; i<produktDaten.length; i+=4){
var entry = {}
for(var j=0; j<dokuArr.length; j+=3){
var seite = dokuArr[j+2];
// make sure seite is a digit
if (!(/^\d+$/.test(seite))){
console.log(seite + ' was not a valid page number')
throw err
}
if (/(A|a)lle?/i.test(nummer)){
entry.kks.pages[beschreibung] = seite;
// })
}
else if (nummer === kksNummer) {
entry.kks.pages[beschreibung] = seite;
}
}
entry.hersteller = produktDaten[i+1]
entry.typ = produktDaten[i+2]
entry.artikelNummer = produktDaten[i+3]
result.push(entry)
}
if (result.length>0){
return accept(result)
}
return reject()
})
})
},
getpageno: function(url){
var self=this
var pdf = pdfjs.getDocument(url);
return pdf.then(function(pdf){
var maxPages = pdf.pdfInfo.numPages;
var countPromises = []; // collecting all page promises
for (var j = 1; j <= maxPages; j++) {
try {
var page = pdf.getPage(j);
var txt = "";
countPromises.push(page.then(function(page) { // add page promise
var textContent = page.getTextContent();
return textContent.then(function(text){ // return content promise
return text.items.map(function (s) { return s.str; }).join('&&&'); // value page text
});
}));
}
catch(e){
console.log(e)
}
}
// Wait for all pages and join text
return Promise.all(countPromises).then(function (texts) {
// since doumentation pages do not add the final '&&&', must add one manually (only after rx has been found)
var fulltext = texts.reduce(function(full, text){
if (rx.test(full)){
var next = '&&&'+text
return full+=next
}
return full+=text
}, '')
return [fulltext, texts]
});
}).then(function(textarr){
var fulltext = textarr[0]
self.fulltext = fulltext;
var texts = textarr[1]
try {
var partialmatch = rx.exec(fulltext)[0]
var count = texts.reduce(function(pageno, text){
var tomatch = text.replace(/.*Typ&&&/, '')
if (tomatch.length>0 && partialmatch.indexOf(tomatch) > -1){
pageno++
}
return pageno;
}, 0)
}
catch(e){
console.log(e)
}
return count;
})
}
Edited the entry to show that I'm now returning the value of the gepageno function.
The data that I am expecting is logged but not available as a result of accept(). Can anyone tell what could be going wrong?
I have tried to simulate and give a solution of your promise. I have posted pseudo code.
Promise flow
var testFunction = ((result) => {
return new Promise(function (resolve, reject) {
var err = null;
if (!!err) {
reject(err);
} else {
console.log("2. testFunction resolved");
resolve("Final response");
}
});
});
var getpageno = ((url) => {
return new Promise((resolve, reject) => {
var err = null;
if (!!err) {
reject(err);
} else {
console.log("1. getpageno resolved");
resolve(45);
}
});
});
var getMetadata = ((text, url) => {
console.log("0. getmetadata resolved");
var self = this;
getpageno(url)
.then((pageCount) => {
console.log("> pageCount :", pageCount);
return testFunction(pageCount);
})
.then((data) => {
console.log(">", data);
});
});
getMetadata("hell", "https://www.google.com");
output
0. getmetadata resolved
1. getpageno resolved
> pageCount : 452. testFunction resolved
> Final response
you need to return the promise on the third line
return self.getpageno(url).then
to access its eventual fulfillment value.

.then promise with sendMessage not working

I have the following code inside a webworker,
onmessage = function(e)
{
var data;
var message = e.data;
sendTimeSeries = false;
var semicolon = message.split(";");
for (var i=0; i<semicolon.length;i++)
{
var colon= semicolon[i].split(":");
for(var j=0; j<colon.length; j++)
{
if(colon[j] == "Insert TimeSeries")
{
stringTimeSeriesTableData = ""
data = colon[j+1].split(" ");
prevLetter = data[0];
getAllRecords(prevLetter).then(addTimeSeries).then(getAllTimeSeries).then(sendMessage); //use of promises
}
}
}
}
The methods getAllRecords, addTimeSeries and getAllTimeSeries are being called in the correct order (won't go into the next method until the previous one has finished executing. However, the sendMessage webworker method is being called before finishing the getAllTimeSeries method.
getAllRecords():
function getAllRecords(letter)
{
var deferred = $.Deferred();
var trans = db.transaction(["ObservableStates"],"readonly").objectStore("ObservableStates").index('letterIndex');
var request = trans.openCursor(IDBKeyRange.only(letter));
request.onsuccess = function(event)
{
cursor = event.target.result;
if(cursor)
{
count = count + 1;
console.log(cursor.value);
addRecordToHistory(cursor.value);
deleteObservableStates(cursor.primaryKey);
while(cursor.continue())
{
}
}
if(cursor==null)
{
console.log('ready from count');
deferred.resolve();
}
}
request.onerror = function(event)
{
console.log('ERROR LOADING DATA FROM TABLE');
}
return deferred.promise();
}
addTimeSeries
function addTimeSeries()
{
var deferred = $.Deferred();
timeSeries = {
l:prevLetter, t:count
}
request = db.transaction(['TimeSeries'], "readwrite").objectStore('TimeSeries').add(timeSeries);
request.onerror = function(event)
{
console.log("Unable to add timeSeries to table TimeSeries");
}
request.onsuccess = function(event)
{
console.log("TimeSeries State Added");
deferred.resolve();
}
return deferred.promise();
}
getAllTimeSeries()
function getAllTimeSeries()
{
var deferred = $.Deferred();
req = db.transaction(['TimeSeries'], "readonly").objectStore('TimeSeries').openCursor();
req.onerror = function(event)
{
console.log("Unable to stringify all records");
}
req.onsuccess = function(event)
{
cursor=event.target.result;
if(cursor)
{
stringTimeSeriesTableData += cursor.value.l + "," + cursor.value.t + ";";
while(cursor.continue())
{
}
}
if(cursor==null)
{
console.log(stringTimeSeriesTableData);
sendTimeSeries = true;
deferred.resolve();
console.log('got all time series');
}
}
return deferred.promise();
}
Is there something I'm missing here? Thanks

Promise function is not running funcation after .then

What I am trying to do is run functions that will send out messages. The problem with node js is that it does not return in sequence. I do however want each function to run in the sequence that it is coded.
Not really sure what I'm missing here.
Right now I can get it to return only message 1 and message 2 in sequence BUT I want to go all the way from callfirstmessage to callfifthmessage. When I have tried to do this they all get returned out of order.
var promise = new Promises(function(resolve, reject) {
// do some async stuff
callfirstmessage();
//resolve(data);
if (success) {
resolve(data);
} else {
reject(reason);
}
});
promise.then(function(data) {
// function called when first promise returned
return new Promises(function(resolve, reject) {
// second async stuff
callthirdmessage();
//resolve(data);
if (success) {
resolve(data);
} else {
reject(reason);
}
});
}, function(reason) {
// error handler
}).then(function(data) {
callsecondmessage();
}, function(reason) {
// second error handler
});
I have looked at a few different posts talking about this topic and I have used those suggestions. I think my issue here is not being able to successfully chain these together. I have spent a few days on this with no additional progress...I need help bad!
-----------------------edit----------------------------
I think I need to apply something similar to this .then I have found here: https://coderwall.com/p/ijy61g/promise-chains-with-node-js. But for some reason it is still sending messages at random.
Maybe, I'm just going in the completely wrong direction. :/
Below is everything I am working with
// dependencies
console.log("starting program");
var async = require('async');
var AWS = require('aws-sdk');
var Converter = require("csvtojson").Converter;
var util = require('util');
var Promises = require('pinkie-promise');
var vow = require('vow');
var s3 = new AWS.S3();
var snsTopicEMAIL = new AWS.SNS({
params: {
TopicArn: 'arn:aws:sns:xxxxxxxxxxxxxxxxxxxxxxxx'
}
});
var snsTopicSMS = new AWS.SNS({
params: {
TopicArn: 'arn:aws:sns:xxxxxxxxxxxxxxxxxxxxxxxxx'
}
});
var abort = false;
//SMS
function topDSRsms(csvJSON) {
var ytdTopReg = "";
if (csvJSON.length < 1) {
console.error("Not enough data records in CSV to compose an SMS. Aborting. count:" + csvJSON.length);
tdTopReg = "There was an error. Please contact IT for assistance.";
abort = true;
throw '';
}
ytdTopReg = "";
for (var i = 0; i < csvJSON.length; i++) {
var csvItem = csvJSON;
if (csvItem[i].KPIvalue.length > 0 && csvItem[i].KPI.length > 0) {
var KPI = " " + csvItem[i].KPI + ":" + csvItem[i].KPIvalue + "\n";
} else {
KPI = " ";
}
if (csvItem[i].TrendValue1.length > 0 && csvItem[i].Trend1.length > 0) {
var trend1 = "\n" + svItem[i].Trend1 + ":" + csvItem[i].csvItem[i].TrendValue1;
} else {
trend1 = "";
}
if (csvItem[i].TrendValue2.length > 0 && csvItem[i].Trend2.length > 0) {
var trend2 = "\n" + csvItem[i].Trend2 + ":" + csvItem[i].TrendValue2;
} else {
trend2 = "";
}
if (csvItem[i].TrendValue3.length > 0 && csvItem[i].Trend3.length > 0) {
var trend3 = "\n" + csvItem[i].Trend3 + ":" + csvItem[i].TrendValue3;
} else {
trend3 = "";
}
ytdTopReg += "\n#" + (i + 1) + KPI + csvItem[i].RankTrend + ":" + csvItem[i].RankTrendValue + trend1 + trend2 + trend3;
}
return ytdTopReg;
}
function dshSmsStr(csvJSON) {
return "DSR:" +
topDSRsms(csvJSON);
}
//email
function topDSREmail(csvJSON) {
var ytdTopReg = "";
ytdTopReg = "Top orders By Region - ";
for (var i = 0; i < csvJSON.length; i++) {
if (csvJSON.length < 1) {
console.error("Not enough data records in CSV to compose an email. Aborting.");
ytdTopReg = "There was an error. Please contact IT for assistance."
abort = true;
throw '';
//return -1;
} else {
var csvItem = csvJSON;
if (csvItem[i].KPIvalue.length > 0 && csvItem[i].KPI.length > 0) {
var KPI = " " + csvItem[i].KPI + ":" + csvItem[i].KPIvalue + "\n";
} else {
KPI = "";
}
if (csvItem[i].TrendValue1.length > 0 && csvItem[i].Trend1.length > 0) {
var trend1 = "\n" + svItem[i].Trend1 + ":" + csvItem[i].csvItem[i].TrendValue1;
} else {
trend1 = "";
}
if (csvItem[i].TrendValue2.length > 0 && csvItem[i].Trend2.length > 0) {
var trend2 = "\n" + csvItem[i].Trend2 + ":" + csvItem[i].TrendValue2;
} else {
trend2 = "";
}
if (csvItem[i].TrendValue3.length > 0 && csvItem[i].Trend3.length > 0) {
var trend3 = "\n" + csvItem[i].Trend3 + ":" + csvItem[i].TrendValue3;
} else {
trend3 = "";
}
ytdTopReg += "\n#" + (i + 1) + KPI + csvItem[i].RankTrend + ":" + csvItem[i].RankTrendValue + trend1 + trend2 + trend3 + "\n";
}
}
return ytdTopReg;
}
function dshEmailStr(csvJSON) {
return "DSR:" +
topDSREmail(csvJSON);
}
console.log("compiled totals string and customer string");
exports.handler = function(event, context) {
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {
depth: 5
}));
var srcBucket = event.Records[0].s3.bucket.name;
console.log("got src bucket name");
// Object key may have spaces or unicode non-ASCII characters.
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
console.log("src key decoded");
// Download the CSV file from S3, Extract&Load data into DynamoDB, and notify end users.
async.waterfall([
function downloadCSV(next) {
// Download the Daily Sales Highlights CSV file from S3 into a buffer.
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
next);
},
function parseCSV(response, next) {
console.log(response.ContentType);
var csvStream = AWS.util.buffer.toStream(response.Body);
var csvJSON = [];
var converter = new Converter({});
//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function(jsonArray) {
console.log(jsonArray); //here is your result jsonarray
csvJSON = jsonArray;
next(null, csvJSON);
});
//read CSV from stream
csvStream.pipe(converter);
},
function updateState(csvJSON, next) {
//Update state in DynamoDB
next(null, csvJSON);
},
function notifyEndUsers(csvJSON, next) {
//Notify end users
console.log("\n\nNotifying SMS end users...\n\n");
console.log(dshSmsStr(csvJSON));
console.log("\n\nNotifying email end users...\n\n");
console.log(dshEmailStr(csvJSON));
//email
snsTopicEMAIL.publish({
Message: dshEmailStr(csvJSON)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
//SMS
var datastr = dshSmsStr(csvJSON);
var strlen = dshSmsStr(csvJSON).length;
var ranscript = false;
var completemsg1 = false;
var completemsg2 = false;
var completemsg3 = false;
var completemsg4 = false;
var completemsg5 = false;
var completemsg6 = false;
function callfirstmessage() {
snsTopicSMS.publish({
Message: dshSmsStr(csvJSON).substring(0, 150)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
return true;
}
function callsecondmessage() {
snsTopicSMS.publish({
Message: dshSmsStr(csvJSON).substring(150, 300)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
return true;
}
function callthirdmessage() {
snsTopicSMS.publish({
Message: dshSmsStr(csvJSON).substring(300, 450)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
return true;
}
function callfourthmessage() {
snsTopicSMS.publish({
Message: dshSmsStr(csvJSON).substring(450, 600)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
return true;
}
function callfifthmessage() {
snsTopicSMS.publish({
Message: dshSmsStr(csvJSON).substring(600, 750)
}, function(err, data) {
if (err) {
console.log(err.stack);
next(err);
}
console.log(data);
next(null);
});
return true;
}
function one() {
new Promises(function(resolve1, reject) {
completemsg1 = callfirstmessage();
if (completemsg1 === true) {
resolve1(true);
console.log('first success');
} else {
reject(false);
console.log('first fail');
}
});
}
function two() {
new Promises(function(resolve2, reject) {
completemsg2 = callsecondmessage();
if (completemsg2 === true) {
resolve2(completemsg2);
console.log('second success');
} else {
reject(false);
console.log('second fail');
}
});
}
function three() {
new Promises(function(resolve3, reject) {
completemsg3 = callthirdmessage();
if (completemsg3 === true) {
resolve3(completemsg3);
console.log('third success');
} else {
reject(false);
console.log('third fail');
}
});
}
function four() {
new Promises(function(resolve4, reject) {
completemsg4 = callfourthmessage();
if (completemsg4 === true) {
resolve4(completemsg4);
console.log('fourth success');
} else {
reject(false);
console.log('fourth fail');
}
});
}
function five() {
new Promises(function(resolve5, reject) {
completemsg5 = callfifthmessage();
if (completemsg5 === true) {
resolve5(completemsg5);
console.log('fifth success');
} else {
reject(false);
console.log('fifth fail');
}
});
}
console.log("\n\n Begin SMS script. Data length :" + strlen + "...\n\n");
if (strlen < 150) { //one message sent
//Will complete later
ranscript = true;
} else if (strlen < 300) { //two messages sent
//Will complete later
ranscript = true;
} else if (strlen < 450) { //three messages sent
//Will complete later
ranscript = true;
} else if (strlen < 600) { //four messages sent
one().then(function() {
return two();
})
.then(function() {
return three();
})
.then(function() {
return four();
})
.then(function() {
return five();
});
ranscript = true;
} else if (strlen < 750) { //five messages sent
//Will complete later
ranscript = true;
} else {
console.log("\n\n The SMS mesages is too large to send to end users...\n\n");
}
if (ranscript === false) {
console.log("\n\n SMS script did not run \n\n");
} else if (ranscript === true) {
console.log("\n\n SMS script successfully ran \n\n");
}
}
], function(err) {
if (err) {
console.error(
'Unable to process due to an error: ' + err
);
} else {
console.log(
'Successfully processed'
);
}
context.done();
});
}
The executor for the first promise (reformatted):
var promise = new Promise(function(resolve, reject)
{ // do some async stuff
callfirstmessage();
if (success)
{ resolve(data);
} else
{ reject(reason);
}
});
doesn't resolve or reject the returned promise asynchronously. You will need to get a call back from the asynchronous operation before resolving/rejecting the returned promise. In pseudo code something more like:
var promise = new Promise(function(resolve, reject)
{ // do some async stuff
callfirstmessage( successCallBack, failCallBack);
function successCallBack( data)
{ resolve(data);
}
function failCallBack( reason)
{ reject(reason);
}
});
In reality you may have to use a call back the asynchronous operation supports, and then analyze success or failure of the operation depending on a status property located in a request or response object.

Why Node.js script doesn't exit

I wrote code to get data from HTTP service and save it in MongoDB.
Now I test it directly from the console node script.js
The script does its job, but it doesn't exit. I have to do CTRL+C to stop it
Why does it not exit automatically? What place in the code is best for process.exit(0) (if it is needed)?
/*global Promise, getData, httpReq, searchData, getHotData, storeData*/
var http = require('http');
var CoubVideo = require('./models/coubdb.js');
function CoubApi (url, numPerPage, numOfPages) {
this.url = url;
this.numOfPages = numOfPages;
this.numPerPage = numPerPage;
this.getData = getData;
this.httpReq = httpReq;
this.searchData = searchData;
this.getHotData = getHotData;
this.storeData = storeData;
}
// Get data from server
function httpReq (url) {
var promise = new Promise (function (resolve, reject) {
http.get(url, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
if(data.length > 0) {
resolve(JSON.parse(data));
} else {
reject("Error: HTTP request rejected!");
}
});
}).on('error', function (err) {
console.log(err);
});
});
return promise;
}
// Store data in MongoDB
function storeData (data, per_page) {
function insertVideoDoc (i) {
CoubVideo.count({id: data.coubs[i].id}, function (err, count) {
if (err) {
console.log(err);
}
if (count === 0 || count === null) {
var video = new CoubVideo(data.coubs[i]);
video.save(function (err) {
if (err) {
console.log(err);
}
console.log("Saved successfully!");
});
} else {
console.log("Duplicate");
}
});
}
var i;
for(i = 0; i < per_page; i++) {
insertVideoDoc(i);
}
}
// Search for coubs
function searchData (searchtext, order, page, per_page) {
var url = this.url +
"search?q=" + searchtext +
"&order_by=" + order +
"&per_page=" + per_page +
"&page=" + page;
this.httpReq(url).then(function (data) {
this.storeData(data, per_page);
}.bind(this));
}
// Get hot coubs
function getHotData (order, page, per_page) {
var url = this.url +
"timeline/hot?page=" + page +
"&per_page=" + per_page +
"&order_by=" + order;
this.httpReq(url).then(function (data) {
this.storeData(data, per_page);
}.bind(this));
}
// Get data
function getData () {
var i;
for(i = 0; i < this.numOfPages; i++) {
this.getHotData("newest_popular", i, this.numPerPage);
}
}
var coub = new CoubApi("http://coub.com/api/v2/", 2, 50);
coub.getData();

Categories

Resources