Reputation: 11809
I have a code below where in I want to finish doSomethingFirst()
before proceeding with the rest of the code:
async doSomething() {
const response = await doSomethingFirst(); // get the response from this first
if(response) {
// rest of the code
}
}
async doSomethingFirst {
const response = await client
.query({
query,
fetchPolicy: "network-only",
variables: {
someVariable: value
}
})
.then(response => {
console.log(response);
})
.catch(err => {
// error
});
return await response;
}
However, the response in doSomething()
comes back as undefined
. What's wrong with this structure?
Upvotes: 1
Views: 6376
Reputation: 1703
Give this a try, normally works for me, if not maybe the problem is elsewhere an it's not returning and actual data?
async doSomethingFirst {
const response = await client
.query({
query,
fetchPolicy: "network-only",
variables: {
someVariable: value
}
})
.then(response => { return response.json();})
.then(responseData => {console.log(responseData); return responseData;})
.catch(err => {
// error
});
}
Upvotes: 1
Reputation: 10652
You should return the response. Anyway, you can just do something like this:
doSomethingFirst() {
return client
.query({
query,
fetchPolicy: "network-only",
variables: {
someVariable: value
}
})
}
async doSomething() {
try {
const response = await doSomethingFirst();
if (response) {
// rest of the code
}
}
catch (err) {
console.log(err)
}
}
A few things you might want to know:
doSomethingFirst
you are using await
and also chaining .then
you don't have to do that because they're the same.doSomethingFirst
a non-async function because since doSomething
is an async function you can just return the promise from doSomethingFirst
and await the response inside doSomething
also error handling can be done with the try-catch blocks as I did.Upvotes: 0