Simple new + then for Q promises - promise

I'm trying to use Q Promise implementation, but am facing strange inconsistency.
When I run in Chrome m33, the following code:
new Promise(function(resolve, reject) {
resolve(1);
}).then(function(value) {
console.log(value);
});
It works just as I expect - it returns another Promise and logs 1.
But if I call the same code wrapped into (function (Promise) { ... }(window.Q));, I see body of resolve callback in console, instead of a value.
Fiddle to look at - works in Chrome and Aurora.
Am I missing something or is it a bug in the library?
PS: Q version 1.0.0

It looks, like Q.promise is a replacement for native Promise, not the Q itself: fiddle.
It's very strange, though. I can't migrate to native promises w/o changing the code later.
Cause Q.promise -> Promise, but Q.all -> Promise.all.

Upgrade to Q v1.0.1 which introduces Q.Promise, which supports a common subset of the ES6 promise interface. Q is analogous to Promise.resolve and new Promise replaces the erstwhile Q.defer(). ES6 did not lift the Q API exactly, but did largely lift the behavior of the analogous functions.

Related

Get first fulfilled promise in RxJS

Similar to Get first fulfilled promise but in RxJS
If I have two promises A and B, only one of which will succeed, how can I get whichever one fulfills successfully? Some of the promises will have rejection as well. Only the successful promise is needed.
I'm looking for something similar to Promise.race, but which will return only the first promise that fulfills. I'm using promises from RxJS6.
RxJS has race also:
import {race} from 'rxjs'
race(promiseA, promiseB).subscribe(result => console.log('winner is ' + result))

Protractor, do I have to use then() after protractor calls?

Is it ok to write:
getFieldX().clear().sendKeys('abc');
or should I write:
getFieldX().clear().then( () => sendKeys('abc));
I'm totally confused about the Promise handling in protractor. clear() returns a promise, so I should use .then() afterwards, shouldn't I?
But I found examples with .then and some without.
Protractor itself has an example without .then():
https://www.protractortest.org/#/control-flow
Does Protractor has its own mechanism and resolves one after the other promise so there is no need for using .then() after a protractor call that returns a Promise?
And is the control flow of protractor only active in a spec?
When using .sendKeys() in a normal function I have to use .sendKeys().then(...) ?
This all depends on if you are using SELENIUM_PROMISE_MANAGER or not. As this is (has?) becoming deprecated, I would not use it. It should be set to false by default, but if you want to be sure you can add SELENIUM_PROMISE_MANAGER = false; to your conf file. The way that protractor has been moving is to use async/await, so your sendKeys function would look like:
let field = element(by.css('CSS.Selector'));
await field.clear();
await field.sendKeys('abc');
Because these are async functions, you will need to define your function properly, so a basic spec would look like:
describe('Demonstrating async/await',function(){
it('Should send some keys', async function(){
let field = element(by.css('CSS.Selector'));
await field.clear();
await field.sendKeys('abc');
});
});
The important difference there is that a function needs to be defined as async function(). As far as reading the code goes, await simply can be read as "Wait until promise resolved to move on". It does get a bit tedious and you feel like you write await before every line of code (you basically do), but I find it significantly better than .then() trees.

How can you mix Parse.Promise with other forms of Promise, e.g. Bluebird / ES6 native Promises?

I want to run some of my Parse Cloud Code on Heroku (Node) to kick start the migration process out of Parse's hosted Cloud Code.
One of the differences between the two environments is the fact that Parse SDK you use is different too. On node, I found that if you do a
var Parse require('parse/node').Parse;
... then Parse.Cloud.httpRequest is actually missing.
I was looking for Node alternatives for performing http requests and found request. But... it doesn't really fit in well with Parse Promises:
parsePromise1()
.then(parsePromise2) // okay
.then(requestPromise) // CUSTOM HTTP REQUEST!
.done(parsePromise3) // this Parse promise always succeeds, and occurs even before the request is fully completed.
I was wondering if anybody had found better ways of converting out of Parse Promises? Thanks.
You can use the request-promise package that wraps request with promises support or a library like bluebird that exposes a method that converts callback APIs to promises.
I recommend that you migrate from Parse promises which are suboptimal to ES2015 native promises (or, more powerful alternatives like bluebird). With those you could:
Promise.resolve(someParsePromise).then(() => // convert
return someParsePromiseFn()// return some Parse promise, that works
}).then(res => {
// more async work ...
});
And avoid .done altogether.
Its not ideal at all, but you can use this kind of wrapper from native Bluebird to native promises:
const Promise = require('bluebird')
function handle () {
return new Promise((resolve, reject) => {
handleWithNativePromise(...arguments)
.then(resolve)
.catch(reject)
})
}

How to convert a promise in protractor to a string

I am a bit new to Protractor and Jasmine, and I am trying to check if a list of elements that I have fetched using getText() contains a particular element:
Consider the following elements
var productNameElements = element.all(by.css('.table-row')).getText();
elementToBeSearched = element(by.css('.table-row .table-row-child(1)')).getText();
Now since both the variables above would return a promise, therefore by doing:
expect(productNameElements).to.eventually.contain(elementToBeSearched);
would fail, and it does fail.
Therefore, I believe that converting elementToBeSearched into a string would be beneficial and would make my life easier. Please suggest a solution on how can I convert a getText() promise to a string. Thanks
Lets say that the element is ele. So the way you should resolve the promise is-
ele.getText().then(function(str){
expect(someOtherElement.getText()).toBe(str);
})
The .then resolves the promise for you. You can confirm the string by puting a console.log(str)before you compare with expect.
PS: The promise inside the expect parenthesis is automatically resolved.
What i did was mostly similar:
productNameElements = element.all(by.css('.table-row')).getText().then(function(name) {
expect(productNameElements).to.eventually.contain(name);
});
This seems to have done the trick for me as I also checked the value of 'name' using console logging
Below code works for me:
let txt = (await elementToBeSearched.then()).toString();

Adding a method to Bluebird promise

I have promisified Mongoose. I have some methods that extent Mongoose Query that now would need to be added to Bluebird. I don't mind extending Mongoose but do not want to take the same approach for this more gobal library. Looking through the docs I see some potentials but I am not sure.
I would like to come as close/clean as the following:
Model.findAsync().toCustom();
toCustom is basically a form of toJSON which 1) execs the query and 2) custom outputs the results/create custom errors etc... pretty straighforward.
What is the cleanest way to achieve something like the above? I would like to avoid doing this each time:
Model.findAsync().then(function(docs) {
return toCustom(docs);
}, function(err) {
return toCustom(err);
});
You get the idea...
Bluebird actually supports your use case directly. If you need to publish a library that extends bluebird in your own custom way you can get a fresh copy of bluebird by doing:
var Promise = require("bluebird/js/main/promise")();
Promise.promisifyAll(require("mongoose")); // promisify with a local copy
Promise.prototype.toCustom = function(){
return this.then(toCustom, toCustom); // assuming this isn't just `.finally`
};
You might also want to export it somehow. This feature is designed for library authors and for getting an isolated copy of bluebird. See the for library authors section in the wiki.

Resources