Reputation: 401
I'm trying to understand promises in JavaScript.
For my example scenario, I want to write a method which either returns data from local "Cache" if available or makes an HTTP call to retrieve the data from server. I always want to return a promise even when no asynchronous calls was made so that user of my JS function has a unified API. How can I achieve that in Javascript. I'm in ES 5.
Upvotes: 0
Views: 52
Reputation: 2040
First promises is ES-6/ecma2015 feature so you have to use something like babel https://babeljs.io/ or even better you can use this pollyfill https://github.com/getify/native-promise-only.
var promise = getValue();
promise.then('do your stuff here ');
function getValue(){
return new Promise(function executor(resolve,error){
getData(resolve); // call your function that gets the data.
});
}
Upvotes: 0
Reputation: 25269
You want them Promise.resolve
function, which takes a value to be immediately resolved. Since you're on es5, you can either use a promise library like Bluebird, or you can use a transpiler like Babel to compile ES6 down to ES5.
Upvotes: 1