This question already has answers here:
How do I return the response from an Observable/http/async call in angular?
(10 answers)
Closed 4 years ago.
I'm getting valid response value from subscriber when I use below code snippets from two different components.
dataService.ts
insertappFormData(){
return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest?i=3').map(this.extractData);
}
private extractData(res: Response) {
return res.text() ? res.json() : {};
}
app.component.ts
this.dataService.insertappFormData().subscribe((response) => console.log(response));
console output
When I'm trying to assign a variable to response value I'm getting 'undefined' error.
myvar:any;
this.dataService.insertappFormData().subscribe(response => this.myvar = response);
console.log(this.myvar);
I have already go through the below discussions.
Solution-1 ,
Solution-2
But I couldn't solve it.
How to solve this problem?
insertappFormData() returns an observable object which is async. It is executed once you invoke subscribe on it and you should print it out inside subscribe() as:
this.dataService.insertappFormData()
.subscribe(response => {
this.myvar = response;
console.log(this.myvar);
});
Because your console.log(this.myvar); is outside of subscribe.
Change to this:
this.dataService.insertappFormData().subscribe(response => {
this.myvar = response;
console.log(this.myvar);
});
Note: subscribe is an asynchrone function.
Related
This question already has answers here:
Async/Await Class Constructor
(20 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have two classes example1 and example2. example1 is having async method inside await keyword and promise response from API. When console inside async function am able to get print this.data and this.data but when I tried this to console inside example2 coming blank response where able to get response for this.key. How to solve this issue. This might be due to resolving promising taking time. Any suggestion ? below is sample example.
One class :
class example1{
constructor(){
this.asyncFunction();
}
async asyncFunction(){
this.key = await this.callAPI(url);
this.data = await this.callAPI(url2);
}
callAPI(url) {
const metadata = new Promise((resolve) => {
fetch(url).then((res) => {
const json = res.json();
// console.log(json);
resolve(json);
});
});
return metadata;
}
}
Second class :
import example1; // just added to show it imported class
class example2{
constructor(){
const a = new example1();
console(a); // i got all response;
console(a.data) // got blank response;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to achieve the URL tracking with below custom made script that extracts the json data that is in array and prints in console.log successfully
function redirecTrace(url){
var urltoprint = [];
fetch("https://redirecttraceservice.com/api/v1/header-checker?initialURL="+url, {
method: "POST"
})
.then(response => response.text()).then((response) => {
var regex = new RegExp(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^"\s]{2,}) - Response 20[01]/);
if(response.match(regex)){
urltoprint = response.match(regex);
console.log(encodeURIComponent(urltoprint[1]));
return ("This is from return: " + urltoprint[1]);
}else{
console.log("Destination URL Not Found");
return "Destination URL Not Found";
}
});
}
So above code prints data in console.log but doesn't returns the data! it always says undefined?
Your return is inside an arrow function inside a promise chain inside the redirecTrace function. So it is returning the value from the inner arrow function, but that does not apply to the outer function. What you want is to also return the promise (put return before the fetch() call). Then you can do this:
redirecTrace(url).then(returnValue => {
// Do something with the returned value
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return values from async functions using async-await from function? [duplicate]
(3 answers)
Closed 3 years ago.
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time
my code is
var DVizModule = (() => {
let dataset = [];
let _data = async () => {
const data = await d3.csv("data/alphabet.csv");
return data;
}
let data = _data().then(data => {
dataset = data;
return dataset;
})
return {
data: data
}
})();
console.log(DVizModule.data);
it returns
Promise pending proto: Promise
PromiseStatus: "resolved"
PromiseValue: Array(26)
When I write
const t = async function() {
const data = await d3.csv("data/alphabet.csv");
return data;
}
t().then(result => console.log(result))
it returns the file perfectly
I'm trying to access the file content via
DVizModule.data
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:
const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.
Hope I got your question right and not trying to resolve the wrong problem ;)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm using a a js lib called teemojs to get information from riot API using node.js and want to store what i get in a var to call back to later, this code
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => console.log(data.id))
gives me what I want but I'm not able to store it in a var to access globally
any ideas on what i can do
P.S I'm trying to say something like this
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => var Result = (data.id))
You have to declare a variable before your promise like
var myVar;
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => {
myVar = data.id;
console.log(myVar); // myVar is defined
})
console.log(myVar); // myVar is undefined
You can also use async/await like
ty {
const {id} = await api.get('euw1', 'summoner.getBySummonerName', playerName);
console.log(id);
} catch (e) {
console.error(e);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I know you can access a Promise’s value inside the .then method like the following code:
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require('fs'));
const mergeValues = require('./helper').mergeValues;
fs.readFileAsync('./index.html', {encoding: "utf8"})
.then((data) => {
return mergeValues(values, data); //async function that returns a promise
})
.then((data) => {
console.log(data);
});
In the above example, I’m reading from a file, merging the data with some values, and then logging the data to the console.
But how about returning the value from a function, as you normally would in a synchronous function? If I follow this comment on synchronous inspection, I think the code should look like this:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
console.log(getView('index.html', null));
But for some reason, it’s not working. All I’m getting in the console is the Promise object itself, not the value. And when I add the .isFulfilled method on modifiedFile, it outputs to true. So I’m not sure what I’m doing incorrectly.
Promises don't work that way. They are asynchronous by nature, so you can't interact with them in the same way you do with synchronous code.
That means you have to use the then method to get at the value:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
// This won't work
// console.log(getView('index.html', null));
// instead:
getView('index.html', null).then(function (view) {
console.log(view);
});
So I’m not sure what I’m doing incorrectly.
You're not doing anything incorrectly, actually. You just can't use promises like a normal return value from a function. Period.