Blue bird return promise missing warning - javascript

I use the following code and I got the warning
Warning: a promise was created in a handler but was not returned from
it
var Promise = require("bluebird");
var glob = Promise.promisify(require('glob'));
glob("files/*.js")
.then(function (files) {
files.forEach(function (file) {
...
invoke(data,response,fn,entity,req);
});
}).catch(function (err) {
console.log('error: ', err);
}
)
what should I do to avoid it?
I read the documentation of BB and it seems that I should return the promise
my question is where? I guess that inside the invoke function but not sure how
This is the inovke function
var invoke = function (data,res,fn,entity,req) {
....
for (var data in entity.app[0]) {
var name = entity.app[0].function;
try {
fn[name](req, res);
}
catch (err) {
res.status(500).send("Error" + err);
}
if (!res.headerSent) {
res.end("done", 200);
}
}
}
}
};
in addition I've tried to return the promise like following which doesnt work
var invoke = function (data,res,fn,entity,req) {
....
return new Promise(function (resolve, reject) {
for (var data in entity.app[0]) {
var name = entity.app[0].function;
try {
resolve(fn[name](req, res));
}
catch (err) {
res.status(500).send("Error" + err);
}
if (!res.headerSent) {
res.end("done", 200);
}
}
}
}
};
I dont want to suppress the warning I want to understand how to solve it...
If I need to add some additional info please let me know, Im stuck here:(

I didn't test the following code but you should have an approach like this:
var Promise = require("bluebird");
var glob = Promise.promisify(require('glob'));
glob("files/*.js").then(function (files) {
return Promise.all(files.map(function (file) {
return invoke(data,response,fn,entity,req);
})
);
}).catch(function (err) {
console.log('error: ', err);
res.status(500).send("Error" + err);
}).finally(function(){
if (!res.headerSent) {
res.end("done", 200);
}
});
var invoke = function (data,res,fn,entity,req) {
return new Promise(function (resolve, reject) {
for (var data in entity.app[0]) {
var name = entity.app[0].function;
try {
fn[name](req, res);
}
catch (err) {
reject(err);
}
}
}
};

Related

How can I return value from this child function in javascript

cannot return the dat[0] value from the inner function
let ite = fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
dat = files.filter(item => item[1] == files.length);
return dat[0];
});
You are returning from the function which will called when the operation will be finished. So returning from that function doesn't change the value of your variable.
You can use readdirSync
const res = fs.readdirSync(directoryPath);
If you don't want it to be sync you can use fs.promises with async await
let res;
(async function() {
res = await fs.promises.readdir("");
})();
I don't recommend to read sync reading because it can block the main thread. You could use a callback function by passing it as parameter to another function.
function getData(onSuccess, onError) {
fs.readdir(directoryPath, function (err, files) {
if (err) {
onError('Unable to scan directory: ' + err);
}
dat = files.filter(item => item[1] == files.length);
onSuccess(dat[0]);
});
}
getData(function(data){
console.log(data);
}, function(error){
//error here
})
We can make it as a promise method to run the code async. Here we don't block any thread. It will be running asynchronously.
function getData(directoryPath) {
return new Promise((resolve, reject) => {
fs.readdir(directoryPath, function (err, files) {
if (err) {
reject('Unable to scan directory: ' + err.message);
}
dat = files.filter(item => item[1] == files.length);
resolve(dat[0]);
});
});
}
getData(directoryPath).then((data) => {
console.log(data);
}).catch((err) => {
console.error(err);
});
// or
try {
let data = await getData(directoryPath);
} catch (error) {
console.error(error);
}

Callback function is not executed within returned Promise

I have two functions that return promise. The first one provide host value, and the second one use the host value to get IP address. I can see that the first function is running without any issue. But looks like the callback function side getHostIps is not executed at all. Not sure why it happens....what's wrong with my promise function?
my promise chain:
getHostedZoneId(dns)
.then(hostZoneId => {
getHostIps(dns, hostZoneId);
})
.then(hostIps => {
logger.Info(hostIps); //hostIps is undefined
})
.catch(err => logger.error(err));
getHostedZoneId:
var getHostedZoneId = function(dns) {
var params = {
DNSName: dns,
};
return new Promise((resolve, reject) => {
findHostZoneByDNS(params, function(err, data) {
if(err) {
reject(err);
}
else {
resolve(data);
}
});
});
}
getHostIps:
var getHostIps = function(dns, hostZoneId) {
var params = {
HostedZoneId: hostZoneId,
StartRecordName: dns,
};
return new Promise((resolve, reject) => {
findHostIps(params, function(err, data) {
//logger.info("get there");
if(err) {
reject(err);
}
else {
resolve(data);
}
});
});
}
I logged hostIps and err and data, all of them are defined. So I am sure that the callback function inside promise is not executed. But not sure how to fix it.
Any feedback is appreciated! Thanks!
You have to return the promise from your then statement to complete the chain.
getHostedZoneId(dns)
.then(hostZoneId => {
return getHostIps(dns, hostZoneId); // Add return
})
.then(hostIps => {
logger.Info(hostIps);
})
.catch(err => logger.error(err));

How to create three function with same name one is callback, second is promise other is async/await

I want to create a function which can be utilised in 3 ways for creating npm dependency
Promise way
callback way
async/await way
For Example
1) async/await
var mongoose = require('mongoose');
async function Connection() {
try {
await mongoose.connect('mongourl');
} catch (err) {
console.error("Connection error --->", err);
}
}
Connection();
2) Callback Style
var mongoose = require('mongoose');
mongoose.connect('mongourl', function (err) {
if (err) console.error("Connection error --->", err);
});
3) Promise Style
var mongoose = require('mongoose');
mongoose.connect('mongourl').then(() => {
}).catch(err => console.error("Connection error --->", err));
Did u absorve that mongoose.connect is same name for all types
You can try with:
const connect = (name, callback) => {
try {
const result = /* generate result */
if (callback) {
callback(null, result);
} else {
return Promise.resolve(result);
}
} catch (e) {
if (callback) {
callback(e);
} else {
return Promise.reject(e);
}
}
}
And quick usage example:
connect('John')
.then(result => { /* ... */ })
.catch(error => { /* ... */ });
connect('John', (error, result) => { /* ... */ });
async function foo() {
try {
const result = await connect('John');
} catch (error) { /* ... */ }
}
Here is an example, it's similar to #hsz, but I've put the handling for the inner callback.
If your pass a callback it does this in a callback way, if not it returns a Promise instead.
If you run the snippet you can see it in action.
I've basically created a simple setTimeout function that randomly fails, to show how error handling is also done. So to see the full effect try running the snippet a few times.
function doInner(name, callback) {
setTimeout(() => {
if (Math.random() < 0.5)
callback(null, "Did " + name);
else callback(new Error("Oops in " + name));
}, 1000);
}
function doSomething(name, callback) {
if (callback) {
doInner(name, (err, result) => {
if (callback) callback(err, result);
});
} else return new Promise((resolve, reject) => {
doInner(name, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
//now lets test both ways
doSomething("test callback", (err, result) => {
if (err) console.error(err);
else console.log(result);
});
(async function () {
try {
const result = await doSomething("Promise");
console.log(result);
} catch(e) {
console.error(e);
}
}());

declaring a function to wait for a promise

I have the following function:
function JSON_to_buffer(json) {
let buff = Buffer.from(json);
if ( json.length < constants.min_draft_size_for_compression) {
return buff;
}
return zlib.deflate(buff, (err, buffer) => {
if (!err) {
return buffer;
} else {
return BPromise.reject(new VError({
name: 'BufferError',
}, err));
}
});
}
I want to be able to run this but have it wait if it goes to the unzip call. I'm currently calling this within a promise chain and it's going back to the chain without waiting for this and returns after the previous promise chain has completed.
You can put that logic into a Promise along with an async function
function JSON_to_buffer(json) {
return new Promise(function (resolve, reject) {
let buff = Buffer.from(json);
if (json.length < constants.min_draft_size_for_compression) {
return resolve(buff);
}
zlib.deflate(buff, (err, buffer) => {
if (!err) {
resolve(buffer);
} else {
reject(err);
/*return BPromise.reject(new VError({
name: 'BufferError',
}, ));*/
}
});
});
}
async function main() {
try {
let buffer = await JSON_to_buffer(myJSON);
} catch (e) {
console.log(e.message);
}
}

How to return string value of items inside file using fs and promises?

i have a doubt, i have this code in js:
var fs = require('fs');
var Promise = require('bluebird');
fs.readFileAsync = function(filename) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, function(err, data){
if (err)
reject(err);
else
resolve(data);
});
});
};
function constructStringArray(nameArray) {
var i = 1;
fs.readFileAsync("./input.txt").then((value) => {
console.log(value);
}).catch((err) => {
console.log("Something goes wrong");
});
}
constructStringArray("test");
And this code returns me this value: .
How can i make to return strings like this:
Adria
Joan
Papo
Thank you.

Categories

Resources