return new Promise never returns [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to use a promise in my function but it never returns. This is my code:
function getData(id) {
return new Promise(function(resolve, reject) {
DbUtil.connection.query("my query... ", [id],
function (error, results, fields) {
if (error) {
reject(error);
} else {
resolve(results);
}
}
);
})
}
The query works and I can see its results in the else block. But the function itself doesn't return. I tried adding a return statement after the resolve, and also after the Promise function itself. But it still doesn't return.
What am I missing?
EDIT: how do I know the function doesn't return? Because
function main() {
var data = getData(1);
console.log("data returned? " + data);
}
in the above main function the log statement is never called.

It's not the proper way to handle a promise
Try this:
var data;
getData(1).then(function(d) {
console.log(d);
data = d;
});
// Since a Promise is async, you can't log data here
or
async function main() {
var data = await getData(1);
console.log(data);
}
Note that this examples does not handle catch case.

Related

Return Result From Query NodeJs [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Hello could someone inform me how do I return the value of a query to use in another class This is my query:
var pconn = require('./db.js');
var dadosMsg = null
function getValueMsg(){
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
return dadosMsg;
} else {
return err;
console.log(err);
}
});
}
I would like to return the query value in this class
var x = require('./dbmsg');
x.getValueMsg();
console.log(x.dadosMsg.valor_msg);
You can use Promise.
A Promises are used to handle asynchronous operations in JavaScript
Promise constructor takes only one argument,a callback function.
Callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well then call resolve.
If desired operations do not go well then call reject.
function getValueMsg() {
return new Promise((resolve, reject) => {
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
resolve(dadosMsg);
} else {
console.log(err);
reject(err);
}
});
});
}
// other file
var x = require('./dbmsg');
//You can consume Promises using then and .catch methods.
x.getValueMsg().then((results)=>{
console.log(results);
}).catch((err)=>{
console.log(err);
})

making a .then() function return a promise to be used by another function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am using this native script firebase plugin, which makes me use this function:
getValue() {
var value;
firebase.getValue('/companies')
.then(result => {
console.log(JSON.stringify(result));
value = result;
return result;
})
.catch(error => {
console.log("Error: " + error);
return error;
});
return value;
}
If I import it in another file and use it like this:
var myValue = this.myFirebaseService.getValue();
If I run it the first time it returns undefined but the second time it returns the value.
My question is how do I make the firebase function return a promise so I can make my second statement wait for it.
The firebase function you're referring to is returning a promise. That's why you can use .then and .catch after calling the getValue function.
If you return the firebase promise from getValue(), like this:
getValue(){
return firebase.getValue('/companies');
}
You'll be able to call getValue() whenever you like, but you'll have to execute the code after getValue() (which is a promise) is resolved. Like so:
getValue().then(function(value) {
console.log(value);
});
I would read up on promises if you don't understand this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
You can initialize myValue after the result has been received from the then block.
Something like this:
var myValue;
function getValue() {
return firebase.getValue('/companies');
}
myValue = getValue().then(result => {
const value = JSON.stringify(result);
console.log(value);
return value;
})
.catch(error => {
console.log("Error: " + error);
});
}

Let a promise return something [duplicate]

This question already has answers here:
How to block for a javascript promise and return the resolved result? [duplicate]
(2 answers)
Closed 5 years ago.
I have to use a method that returns a promise and that is inside a function. I want to return a value for the parent function in the .then() of the promise.
returnSomething():boolean{
theFunctionThatReturnsAPromise()
.then(
//return true for the returnSomething function here
).catch(
//return false for the returnSomething function here
);
}
How can I do this with typescript/Javascript?
You can use async/await for this.
async function foo() {
try {
var val = await theFunctionThatReturnsAPromise();
console.log(val);
}
catch(err) {
console.log('Error: ', err.message);
}
}
But the return value is still going to be a Promise, since it is asynchronous.
For a better understanding you might want to read this tutorial.
You can't return something directly because the thing you want to return isn't immediately available. That's the whole reason we use asynchronous things like promises. It's hard to know exactly what you are doing from a couple lines of code, but in general you just want to return the promise and allow the caller of the function to deal with it.
For example:
returnSomething():Promise<boolean>{
return theFunctionThatReturnsAPromise()
}
Then the caller can deal with the value like:
returnSomething()
.then(result => {
if (result) { //etc.}
}
.catch( err => { console.log("an error happened", err)}

How to return a value in Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am relatively new to Javascript and I really don't understand what I am doing wrong here but the return value is not being set :
found = _dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true
} else {
found = false
}
}
return found
});
As you are using callback functions (the function in the last parameter in findOne), to return results, I sugest to you to use a callback function.
To get the result, you may do something like:
function myFunction(myParams, callback){
_dataDictionary.findOne(myParams, function(err,result){
return callback(err,result);
});
}
Then you can call "myFunction" in other place like:
...
myFunction(params, function(err,result){
//do something with the result)
}
OBS1: if the params are an another function, the "ugly" way to do this is using nested callbacks, that usually are a "antipattern".
function myFunction(myParams, callback){
_dataDictionary.findOne(myParams, function(err,result1){
_anotherAsyncFunction(result1.params, function(err,result2){
//do something with result2 and callback it.
});
});
}
OBS2: You can avoid this antipattern using libraries such async "waterfall" method or bluebird Promise Library "then" methods.
It appears that _dataDictionary.findOne is an asynchronous function. So the value returned from the statement is not the same as the one assigned later inside the callback.
Refactoring your example will hopefully show you this:
_dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true
} else {
found = false
}
}
// This statement returns to the `findOne` line executing this callback
// return found;
// Instead you can log here to see the value
console.log('FOUND', found);
});
UPDATE: based on your comments (and a few more assumptions) you could refactor to provide the value back to the calling function:
Model.observe('access', function(ctx, next, cb) {
var _dataDictionary = loopback.findModel('dataDictionary');
_dataDictionary.findOne(findByModelNameQuery, function(err, result) {
if (result) {
if (result.record) {
found = true;
} else {
found = false;
}
}
// Assuming cb is the method to return values if async
cb(found);
});
// Assuming this is for async behavior to notify to the `observe` caller that this is an async callback
next();
});

Javascript promise return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm trying to make a function that returns the body of an api call using a promise. My code is
function checkApi(link) {
var promise = new Promise(function(resolve, reject) {
//query api
});
promise.then(function(value) {
console.log(value); //want to return this, this would be the body
}, function(reason) {
console.log(reason); //this is an error code from the request
});
}
var response = checkApi('http://google.com');
console.log(response);
Instead of doing console log, I want to return the body of google.com so that I can use it. This is just a scope problem, but I'm not sure how to fix it. Thanks,
You can return the promise and then when you call the checkApi you can attach another .then().
function checkApi(link) {
var promise = new Promise(function(resolve, reject) {
//query api
});
return promise.then(function(value) {
console.log(value); //Here you can preprocess the value if you want,
//Otherwise just remove this .then() and just
return value; //use a catch()
}, function(reason) {
console.log(reason); //this is an error code from the request
});
}
//presuming this is not the global scope.
var self = this;
checkApi('http://google.com')
.then(function (value){
// Anything you want to do with this value in this scope you have
// to do it from within this function.
self.someFunction(value);
console.log(value)
});

Categories