Implement a "promise always" return function - promise

So i have these 2 functions loadScriptWithBluebird and loadBluebird,
loadScriptWithBluebird is supposed to be generic for the main flow of the application, and will always return a promise. I wonder if it is possible with some kind of a pattern to use loadBluebird inside loadScriptWithBluebird
function loadBluebird(callback){
//load the script and callback ...
script.onload = function() {
callback();
};
}
function loadScriptWithBluebird (src){
if(isBluebirdAvailable()){
return new Bluebird(function(resolve, reject){
//load the script and resolve ...
script.onload = function() {
resolve();
};
});
}else{
//issue starts here since i obviously cannot return inside the callback
loadBluebird(function(){
loadScriptWithBluebird(src)
})
}
},
So the flow of the application will look like this :
loadScriptWithBluebird('jquery').then(function(){
//...
});
Thanks.

No, you can't do that, since bluebird wouldn't yet be available when you need to return the promise. So simply ignore that, and rely on the caller of your loadScript function to already have loaded Bluebird. There's not really a way around this.

Related

Cypress returning Synchronous value within Async command?

So I think this is probably me mixing up sync/async code (Mainly because Cypress has told me so) but I have a function within a page object within Cypress that is searching for customer data. I need to use this data later on in my test case to confirm the values.
Here is my function:
searchCustomer(searchText: string) {
this.customerInput.type(searchText)
this.searchButton.click()
cy.wait('#{AliasedCustomerRequest}').then(intercept => {
const data = intercept.response.body.data
console.log('Response Data: \n')
console.log(data)
if (data.length > 0) {
{Click some drop downdowns }
return data < ----I think here is the problem
} else {
{Do other stuff }
}
})
}
and in my test case itself:
let customerData = searchAndSelectCustomerIfExist('Joe Schmoe')
//Do some stuff with customerData (Probably fill in some form fields and confirm values)
So You can see what I am trying to do, if we search and find a customer I need to store that data for my test case (so I can then run some cy.validate commands and check if the values exist/etc....)
Cypress basically told me I was wrong via the error message:
cy.then() failed because you are mixing up async and sync code.
In your callback function you invoked 1 or more cy commands but then
returned a synchronous value.
Cypress commands are asynchronous and it doesn't make sense to queue
cy commands and yet return a synchronous value.
You likely forgot to properly chain the cy commands using another
cy.then().
So obviously I am mixing up async/sync code. But since the return was within the .then() I was thinking this would work. But I assume in my test case that doesn't work since the commands run synchronously I assume?
Since you have Cypress commands inside the function, you need to return the chain and use .then() on the returned value.
Also you need to return something from the else branch that's not going to break the code that uses the method, e.g an empty array.
searchCustomer(searchText: string): Chainable<any[]> {
this.customerInput.type(searchText)
this.searchButton.click()
return cy.wait('#{AliasedCustomerRequest}').then(intercept => {
const data = intercept.response.body.data
console.log('Response Data: \n')
console.log(data)
if (data.length) {
{Click some drop downdowns }
return data
} else {
{Do other stuff }
return []
}
})
}
// using
searchCustomer('my-customer').then((data: any[]) => {
if (data.length) {
}
})
Finally "Click some drop downdowns" is asynchronous code, and you may get headaches calling that inside the search.
It would be better to do those actions after the result is passed back. That also makes your code cleaner (easier to understand) since searchCustomer() does only that, has no side effects.
you just need to add return before the cy.wait
here's a bare-bones example
it("test", () => {
function searchCustomer() {
return cy.wait(100).then(intercept => {
const data = {text: "my data"}
return data
})
}
const myCustomer = searchCustomer()
myCustomer.should("have.key", "text")
myCustomer.its("text").should("eq", "my data")
});

Vuex store action from Promise to async/await

Currently I use promises in the store actions but want to convert it into async/await. This is an example of the store action with promises:
fetchActiveWorkspace (context, workspaceID) {
if (workspaceID) {
return this.$axios.get(`#api-v01/workspaces/workspace/${workspaceID}`)
.then(response => {
context.commit('setActiveWorkspace', response.data)
})
.catch(err => {
throw err
})
} else {
return Promise.resolve(true)
}
},
This fetchActiveWorkspace action is resolved in components because it returns promise. How can I convert this code snippet into a async/await structure and use it in components?
This is how I would try to translate it; take into account that as I have no access to the original code in full context, I cannot try it first-hand to make sure it works; but still, this is how you can use async/await with promises.
// 1. Mark the function as `async` (otherwise you cannot use `await` inside of it)
async fetchActiveWorkspace(context, workspaceID) {
if (workspaceID) {
// 2. Call the promise-returning function with `await` to wait for result before moving on.
// Capture the response in a varible (it used to go as argument for `then`)
let response = await this.$axios.get(`#api-v01/workspaces/workspace/${workspaceID}`);
context.commit('setActiveWorkspace', response.data);
}
// 3. I don't think this is necessary, as actions are not meant to return values and instead should be for asynchronous mutations.
else {
return true;
}
}
You can surround the function's body with try/catch in case you want to capture and handle exceptions. I didn't add it in order to keep things simple and because your promise-based code will just capture and re-throw the exception, without doing anything else.

Ecma 6 Promise complete

I am experimenting with Promise from ES6, but I can't find any alternative to complete as in jQuery ajax. I need to execute function after all the registered handlers with "then".
Thanks!
As mentioned by Bergi, what you want is the disposer pattern. Your central conception of a promise appears to be a bit off, and I think that is making this harder for you to reason about. When you call .then, you are not conceptually "attaching a handler", you are creating a new promise that will by definition resolve after all of its .then handlers have run.
Given your central issue based on code like this:
// a.js
module.exports = function(){
// Where 'Promise.resolve()' is a stand in for your ajax.
return Promise.resolve()
.then(function(){
// Want this to run after 'B'.
});
}
// b.js
var makePromise = require('./a');
module.exports = function specialMakePromise(){
return makePromise().then(function(){
// Should run first.
});
}
They will always run in the wrong order, because by definition, the .then handler from a.js must run and complete before the .then handler from b.js.
One way to approach this problem would instead to structure your code like this:
// a.js
module.exports = function(callback){
return Promise.resolve()
.then(callback)
.then(function(){
// Want this to run after 'B'.
});
}
// b.js
var makePromise = require('./a');
module.exports = function specialMakePromise(){
return makePromise(function(){
// Should run first.
});
}

promises and deferred in ajax and jquery

This is a sample functionality I need, is it possible??. I am facing problem in debugging it
I need those two functions to be ran before I do any other modification how to do it?
function getPromise() {
var deferred = $.Deferred();
$.when(getPromiseother()).done(function() {
deferred.resolve();
});
deferred.getPromiseother()
}
function getPromise() {
var deferrednext = $.Deferred();
$.when($.ajax(somefunction)).done(function() {
deferrednext.resolve();
});
deferrednext.promise()
}
$.when(getPromise).done(function() {
do something
});
This is a very clumsy way to do this - basically a major point of promises is that they compose and chain and you don't need to $.Deferred anywhere that's not converting a callback API to promises.
$.when($.ajax(somefunction), someOtherPromise).then(function(result, other){
// in here both promises have run to fulfillment and data is available
// so place the rest of your code here
});

what is the difference between thunk, futures, and promises?

There are wiki articles about them: (http://en.wikipedia.org/wiki/Futures_and_promises, http://en.wikipedia.org/wiki/Thunk_(delayed_computation)). But I am not sure what are the exact differences between the three as a programming language concept? Are futures and promises only applicable in concurrent programming?
An example of each, using javascript since everybody can read it.
Please don't use this code in production, use a real library, there are plenty of good ones.
var a, b, c, async_obj; // assume exist
// CommonJS - for reference purposes
try {
async_obj.asyncMethod(a, b, c, function (error1, result1) {
if (error1) {
console.error(error1);
} else {
console.log(result1);
}
});
} catch (ex1) {
console.error(ex1);
}
// Thunk - "a parameterless closure created to prevent the evaluation of an expression until forced at a later time"
function makeThunkForAsyncMethod (cb) {
return function () {
async_obj.asyncMethod(a, b, c, cb);
}
}
var my_thunk = makeThunkForAsyncMethod(function (error1, result1) {
if (error1) {
console.error(error1);
} else {
console.log(result1);
}
});
setTimeout(function () {
try {
my_thunk();
} catch (ex1) {
console.error(ex1);
}
}, 5e3);
// Promise - "a writable, single assignment container which sets the value of the future"
function makePromiseForAsyncMethod () {
var
future_then_cb,
future_catch_cb,
future
;
future = {
then: function (cb) {
future_then_cb = cb;
},
catch: function (cb) {
future_catch_cb = cb;
};
};
try {
async_obj.asyncMethod(a, b, c, function (error1, result1) {
if (error1) {
if (future_catch_cb) {
future_catch_cb(error1)
}
} else {
if (future_then_cb) {
future_then_cb(result1);
}
}
});
} catch (ex1) {
setTimeout(function () {
if (future_catch_cb) {
future_catch_cb(ex1);
}
});
}
return future;
}
// Future - "a read-only placeholder view of a variable"
var my_future = makePromiseForAsyncMethod();
my_future
.then(function (result) {
console.log(result);
})
.catch(function (error) {
console.error(error);
})
;
A Promise chain would be like the above contrived example, but it would work on collections and be more robust.
in functional programming, the most difference between thunk and promise is, thunk is pure while promise is impure.
function thunkDemo() {
return function(callback) {
asyncMethod(someParameter, callback);
};
}
function promiseDemo() {
return new Promise(function(resolve, reject) {
asyncMethod(someParameter, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
}
when thunkDemo is called, the asyncMethod will not be called until the inner method called, so thunkDemo is pure with no side affect.
when promiseDemo is called, it will call asyncMethod immediatly, which means, it's not pure.
Thunk is a general concept of a small function which is used only to adapt the call or prepare/modify it in some way and then redirect to the proper function. Things like promises, futures, closures, wrappers, stubs or implementations of the concept of virtual function tables in some OO languages (like C++) are just special use cases of thunks (thunks are often used to implement them).
These are quite broad terms, and their usage and interpretations vary with context. So a specific answer can only be given for a specific context.
In javascript promise libraries for example, the terms "deferred" and "promise" are used for what your linked wiki article refers to as "promise" and "future" respectively, in that a "deferred" is the interface for resolving or rejecting the value, and "promise" is the interface for reading it, with some more specifics that allow easily constructing new promises for dependent values, but not actually changing the original promise.
I just stumbled upon the JS library "co" (https://github.com/visionmedia/co).
It was the first time I heard of "thunks", and it seems to be using the term in a slightly different sense from slf's answer, and much more specific than your linked wiki as well. It is not a parameterless function that returns the value, it is a function accepting a callback that will call the callback with the value, often asynchronously.
In this specific library's case, thunks and promises are very close to each other: a promise is an object with a "then" method function that sets a callback for getting the value; a thunk is directly a function that sets a callback for getting the value.

Resources