Reputation: 1662
So I'm working on a code skeleton for an assignment to make a react app. Got a function that looks like this:
this.asyncFunction = function () {
const url = 'https://api.com/stuff/get'
return fetch(url, httpOptions)
.then(processResponse)
.catch(handleError)
}
It gets called like this
model.asyncFunction().then(stuff => {
this.setState({
status: 'LOADED',
stuff: stuff
})
}).catch(() => {
this.setState({
status: 'ERROR'
})
})
My question (which I'm not sure of how to google for) I want to cache the result and if it's cached I want to result that one. I tried what I felt was most obvious:
this.asyncFunction = function () {
if(cached){
return cachedResult;
}
const url = 'https://api.com/stuff/get'
return fetch(url, httpOptions)
.then(processResponse)
.catch(handleError)
}
(and storing the cachedResult in the processResponse function)
Now this doesn't work, I get
TypeError: ... asyncFunction(...).then is not a function
Now, from google I've learned that this is because asyncFunction should return a promise (since we call it followed by a "then"). What is the "right way" of doing this?
Kind of assuming this is some form of duplicate but not sure how to go about finding it. I've tried around with creating a promise with resolve, but it looks like that only returns undefined.
Upvotes: 0
Views: 267
Reputation: 6482
I think you can do the following:
this.asyncFunction = function () {
if(cached){
return Promise.resolve(cachedResult);
}
...etc
From the docs:
The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; if the value was a promise, that object becomes the result of the call to Promise.resolve; otherwise the returned promise will be fulfilled with the value.
In your scenario, you are returning an object so it will return a Promise object that will resolve with the given object.
Upvotes: 4