/    Sign up×
Community /Pin to ProfileBookmark

Return values from fetch()

I have managed to get the PUT method to work:
https://jsfiddle.net/mq7b0tzs/5/

But now I am trying to understand how I can get JSON values in return using method GET:
https://jsfiddle.net/w7y6dgxk/1/

How do I put values in an outside variable for use in another function?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJul 17.2022 — @sibert#1645406 >How do I put values in an outside variable for use in another function?

This is not possible as fetch is working asynchronously. Your function will always return a promise that has to be resolved:
``<i>
</i> let body = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
};

function chg_status(url, body) {
return fetch(url, body)
.then(response =&gt; response.json())
.then(obj =&gt; obj)
};
let answer = chg_status("https://api3.go4webdev.org/usr/all", body)
answer.then(obj =&gt; {
console.log(obj);
});<i>
</i>
``

Formerly, at times of XMLHttpRequest, it was possible to switch to sychronous mode but using this was not recommended.
Copy linkTweet thisAlerts:
@sibertauthorJul 21.2022 — > @Sempervivum#1645408 This is not possible as fetch is working asynchronously

Could this be a solution to "pass" a variable to another function?

https://jsfiddle.net/sf3jg5L6/
Copy linkTweet thisAlerts:
@SempervivumJul 21.2022 — Yes, when processing is done inside a function, this is possible.

A different option is handing over the function or it's reference to chg_status:
``<i>
</i> function chg_status(url, body, callback) {
fetch(url, body)
.then(response =&gt; response.json())
.then(obj =&gt; {
callback(obj);
})
}

function another(answer) {
alert(JSON.stringify(answer))
}
chg_status("https://api3.go4webdev.org/usr/all", body, another)<i>
</i>
``
×

Success!

Help @sibert spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...