Porting Promise Chaining from AngularJs to VueJs - javascript

Similar to my last question but different enough that I am at a loss. I have the following function in AngularJs that I need to recreate in VueJs. I have two similar ways I've tried to write this in VueJs, but they are causing lots of site exceptions both ways.
AngularJs
var foo = function(obj, config) {
if (config.skip) {
return $q.reject("Skipping");
}
var deferred = $q.defer();
obj.promise = deferred.promise;
if (obj.hasValue()) {
deferred.resolve(obj);
} else {
"/api/callToApi".$promise.then(function(res) {
if (res) {
deferred.resolve(res);
else {
deferred.reject(res);
}
});
}
return deferred.promise;
}
VueJs - take 1. I'm pretty sure this one is missing the actual promise chaining, not sure how to correctly set that.
var foo = function(obj, config) {
let returnEarly = false;
let promise = new Promise((resolve, reject) => {
returnEarly = true;
reject("Skipping"):
}
if (returnEarly) {
return promise;
}
obj.promise = promise;
return new Promise((resolve, reject) => {
if (obj.hasValue()) {
resolve(obj);
} else {
axios.get("/api/callToApi").then(function(res) {
if (res) {
resolve(res);
} else {
reject(res);
}
}
}
}
}
Console errors with take 1
Uncaught (in promise) Error: Request failed with status code 404
at XMLHttpRequest.__capture__.onreadystatechange
VueJs - take 2. I thought this way would return the correct chaining, but I get an error Timeout - Async callback was not invoked within the 5000ms timeout when running jest tests.
var foo = function(obj, config) {
let returnEarly = false;
let promise = new Promise((resolve, reject) => {
returnEarly = true;
reject("Skipping"):
}
if (returnEarly) {
return promise;
}
obj.promise = promise;
return promise.then(() => {
return new Promise((resolve, reject) => {
if (obj.hasValue()) {
resolve(obj);
} else {
axios.get("/api/callToApi").then(function(res) {
if (res) {
resolve(res);
} else {
reject(res);
}
}
}
}
}
}

This is plain JavaScript, not specific to Vue.
It's generally unnecessary to assign a promise to obj.promise because it's returned from the function.
Excessive use of new Promise is known as promise constructor antipattern. If there's already a promise (Axios returns one), there's no need to create a new one, this results in redundant and error-prone code (this can be the reason for Async callback was not invoked... error). In case a new promise needs to be created, there are shortcut Promise methods.
Should be something like:
function(obj, config) {
if (config.skip) {
return Promise.reject("Skipping");
}
if (obj.hasValue()) {
return Promise.resolve(obj);
} else {
return axios("/api/callToApi").then(function(res) {
if (res)
return res;
else
throw res;
}
});
}
}
It's a bad practice in general to make errors anything but Error object.
Also notice that Axios response object is always truthy, possibly needs to be res.data.
Will be more concise when written as async..await.

Related

Am I chaining Promises correctly or committing a sin?

I have not worked with Javascript in a long time, so now promises are a new concept to me. I have some operations requiring more than one asynchronous call but which I want to treat as a transaction where steps do not execute if the step before failed. Currently I chain promises by nesting and I want to return a promise to the caller.
After reading the chaining section of Mozilla's Using Promises guide, I'm not sure if what I'm doing is correct or equivalent to the "callback pyramid of doom".
Is there a cleaner way to do this (besides chaining with a guard check in each then)? Am I right in my belief that in Mozilla's example it will execute each chained then even when there is an error?
myfunction(key) => {
return new Promise((outerResolve, outerReject) => {
return new Promise((resolve, reject) => {
let item = cache.get(key);
if (item) {
resolve(item);
} else {
//we didnt have the row cached, load it from store
chrome.storage.sync.get(key, function (result) {
chrome.runtime.lastError
? reject({ error: chrome.runtime.lastError.message })
: resolve(result);
});
}
}).then((resolve) => {
//Now the inner most item is resolved, we are working in the 'outer' shell
if (resolve.error) {
outerReject(resolve);
} else {
//No error, continue
new Promise((resolve, reject) => {
chrome.storage.sync.get(keyBasedOnPreviousData, function (result) {
chrome.runtime.lastError
? reject({ error: chrome.runtime.lastError.message })
: resolve(result);
});
}).then((resolve) => {
//finally return the result to the caller
if (resolve.error) {
outerReject(resolve);
} else {
outerResolve(resolve);
}
});
}
});
});
}
Subsequent then statements are not executed (until a catch) when an exception is thrown. Also, .then returns a Promise, so you don't need to create an additional, outer Promise.
Try this example:
var p = new Promise((resolve, reject) => {
console.log('first promise, resolves');
resolve();
})
.then(() => {
throw new Error('Something failed');
})
.then(() => {
console.log('then after the error');
return('result');
});
p.then(res => console.log('success: ' + res), err => console.log('error: ' + err));
You will not see "then after the error" in the console, because that happens after an exception is thrown. But if you comment the throw statement, you will get the result you expect in the Promise.
I am not sure I understand your example entirely, but I think it could be simplified like this:
myfunction(key) => {
return new Promise((resolve, reject) => {
let item = cache.get(key);
if (item) {
resolve(item);
} else {
//we didnt have the row cached, load it from store
chrome.storage.sync.get(key, function (result) {
chrome.runtime.lastError
? throw new Error(chrome.runtime.lastError.message)
: resolve(result);
});
}
}).then((previousData) => {
// keyBasedOnPreviousData is calculated based on previousData
chrome.storage.sync.get(keyBasedOnPreviousData, function (result) {
chrome.runtime.lastError
? throw new Error(chrome.runtime.lastError.message)
: return result;
});
});
}
It's a bit of a mess. This is my attempt at rewriting. A good thing to try to avoid is new Promise().
function chromeStorageGet(key) {
return new Promise( (res, rej) => {
chrome.storage.sync.get(key, result => {
if (chrome.runtime.lastError) {
rej(new Error(chrome.runtime.lastError.message))
} else {
res(result)
}
});
});
});
function myfunction(key) {
const item = cache.get(key) ? Promise.resolve(cache.get(key)) : chromeStorageGet(key);
return item.then( cacheResult => {
return chromeStorageGet(keyBasedOnPreviousData);
});
}
Why avoid new Promise()?
The reason for this is that you want to do every step with then(). If any error happened in any of the promises, every promise in the chain will fail and any subsequent then() will not get executed until there is a catch() handler.
Lots of promise based-code requires no error handlers, because promise-based functions always return promises and exceptions should flow all the back to the caller until there is something useful to be done with error handling.
Note that the exceptions to these 2 rules are in my chromeStorageGet function. A few notes here:
new Promise can be a quick and easy way to convert callback code to promise code.
It's usually a good idea to just create a little conversion layer for this callback-based code. If you need chrome.storage.sync in other places, maybe create a little utility that promisifies all its functions.
If there is only 1 'flow', you can just use a series of then() to complete the process, but sometimes you need to conditionally do other things. Just splitting up these complicated operations in a number of different functions can really help here.
But this:
const result = condition ? Promise.resolve() : Promise.reject();
Is almost always preferred to:
const result = new Promise( (res, rej) => {
if (condition) {
res();
} else {
rej();
}
}

Recursive promise not resolving

I have a function that fetches some data. If data is not available (it becomes available after some short time), it returns null. I created a function, that returns promise, which is wrapped around logic that fetches data and checks if it is is available - if not, it calls itself:
Foo.prototype.fetchDataWrapper = function () {
return new Promise((resolve, reject) => {
const data = fetchData();
if (data) {
resolve(data)
} else {
setTimeout(() => {
return this.fetchDataWrapper()
}, 100)
}
})
}
Problem is, that despite data is fetched correctly, this promise never resolves. What am I doing wrong?
Your return this.fetchDataWrapper() is returning from the timer callback, no fetchDataWrapper. fetchDataWrapper has already returned. Instead, pass that promise into resolve:
Foo.prototype.fetchDataWrapper = function () {
return new Promise((resolve, reject) => {
const data = fetchData();
if (data) {
resolve(data);
} else {
setTimeout(() => {
resolve(this.fetchDataWrapper()); // *****
}, 100);
}
})
};
When you pass a promise to resolve, it makes the promise resolves belong to resolve or reject based on the promise you pass to it.
(I've also added some missing semicolons to that code. I recommend being consistent with semicolons: Either rely on ASI or don't, both don't mix the two. Also recommend not relying on ASI, but that's a style choice.)
Side note: It would probably make sense to reject after X attempts, perhaps:
Foo.prototype.fetchDataWrapper = function (retries = 5) {
// *** Declare retries param with default -^^^^^^^^^^^
return new Promise((resolve, reject) => {
const data = fetchData();
if (data) {
resolve(data);
} else {
if (retries) { // *** Check it
setTimeout(() => {
resolve(this.fetchDataWrapper(retries - 1));
// *** Decrement and pass on -^^^^^^^^^^^
}, 100);
} else {
reject(); // *** Reject
}
}
})
};

How to use another promise in a function which returns a new promise?

I started learning Promises in JS and I am trying to replace my existing callback logic using promises. I wrote a function which returns a new promise, and also uses a promise of a database instance to retrieve the data. However, i am not sure if i am doing it right. Here is the code snippet,
usersService.js
var getUsers = function(queryObject) {
return new Promise(function(resolve, reject) {
dbConnection.find(queryObject)
.then(function(result) {
if (result.length > 0) {
resolve(result)
} else {
resolve(errorMessage.invalidUser())
}).catch(function(err) {
reject(err)
});
})
};
usersRouter.js
router.get('/users', function (req,res,next) {
var queryObject = { "userId":req.query.userId };
userService.getUsers(queryObject)
.then(function (data) { //some logic })
.catch(function (err) { //some logic });
});
Can i use resolve conditionally ?
If the answer is No, what is the right approach ?
Also, am i using the promise in a right manner, in the router?
Thanks in advance!
Since dbConnection.find returns a promise, you can return it directly and choose what will be pass when you will resolve it. No need to wrap it inside an other promise.
var getUsers = function (queryObject) {
return dbConnection.find(queryObject).then(function (result) {
if (result.length > 0) {
return result
} else {
return errorMessage.invalidUser()
}
})
};

Using Promises in NodeJS (Parse Server)

I am trying to get used to Promises. My Parse Server environment always returns a promise, however I need to mix Parse functions with some of my own functions that I would like to work in accordance with the Parse way of doing things.
Here is my code
savePrescription(user, prescription)
//Returning an object (working!) to be passed to the next function.
.then(function(savedProgData) {
console.log(savedProgData) <-- undefined!
getSavedData(savedProgData)
})
.then(function(savedIds) {
console.log(savedIds); <-- undefined!
sendClientProgrammes(savedIds)
})
.then(function(returnedData) {
console.log(returnedData);
response.success();
}, function(err) {
response.error(err);
})
function sendClientProgrammes(savedIds) {
console.log('running send client programmes');
return new Promise(function(resolve, reject) {
return resolve();
})
}
function getSavedData(savedProgData) {
console.log('running getSavedData');
return new Promise(function(resolve, reject) {
var savedIds = [];
for(var i = 0; i < savedProgData.length; i++) {
savedIds.push(savedProgData[i].id)
}
if(savedIds.length > 0) {
console.log(true);
return resolve(savedIds);
} else {
reject();
}
})
}
At the end of this I am getting a {code: 107, message: "The server returned an invalid response."} error.
How can I 'promisfy' my standard JS functions?
You need to return the results of your functions so the promises are passed down.
.then(function(savedProgData) {
return getSavedData(savedProgData)
})

ES6 generator functions in angular

recently I started using generators in my angular project. Here's how I do it so far:
function loadPosts(skip) {
return $rootScope.spawn(function *() {
try {
let promise = yield User.findAll();
$timeout(function () {
// handle the user list
});
} catch (err) {
// handle err
}
});
}
From what I've read the next part won't be necessary in es7, but currently I have the spawn function in the run block of my app.
$rootScope.spawn = function (generatorFunc) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc();
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
};
Everything works find the way I do it at the moment, the only thing I really don't like is that I have to call $timeout() after each promise. If I don't my $scope variables initialized inside the timeout won't be initialized. It seems to me that angular digest system needs to be triggered manually.
Why is that and is there a way to make this cleaner?
I would assume it is because your spawn method uses native Promises, not the angular implementation. Try to use $q instead:
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return $q.reject(err);
}
if (result.done) {
return result.value;
} else {
return $q.resolve(result.value).then(onFulfilled, onRejected);
}
}

Categories

Resources