mongodb-es6 promise not working - javascript

I am playing around mongodb-es6-master, in which it was written that mongoClient.connect() returns a promise, but i am not able to invoke the 'then' function on that promise.
i have a file named index.js
which i am invoking with node version 5.0.
following is the code snippet. Am i missing anything?
'use strict'
var co = require('co');
var MongoClient = require('mongodb-es6').MongoClient;
co(function* (){
let client = yield new MongoClient("mongodb://localhost:27017/test", {}).connect();
var collectionP = yield client.then((value) => {
//some code
// console throws [TypeError]client.then in not a function

Related

How to assign variable to result of asynchronous class method that returns an object in its promise?

Looks nobody on internet describes similar problem, and similar solution is not working for me.
I am trying to scrape webpage so I created class for parser and one of the method looks like follows:
get chListUrl() {
return "http://www.teleman.pl/program-tv/stacje";
}
getChannels() {
var dict = {};
axios.get(this.chListUrl).then(function (response) {
var $ = cheerio.load(response.data);
var ile_jest_stacji = $('#stations-index a').length;
$('#stations-index a').each( (i,elem) => {
let href = $(elem).attr('href');
let kodstacji = href.replace(/\/program-tv\/stacje\//ig,'');
let nazwastacji = $(elem).text();
dict[nazwastacji]=kodstacji;
});
return dict;
}).catch(function (error) {
console.log(error);
return null;
}).finally(function() {
console.log("Koniec");
});
}
And problem is getChannels must be indirectly asynchronous because it contains axios BUT
let tm = new TM();
var a = tm.getChannels();
a is always undefined and it should be dictionary! Such construct means "assing to variable a result of execution of tm.getChannels()" so assignment should always be done AFTER whole function ends. Otherwise such syntax in language is useless because you will never be sure what value is stored in variable, and such errors are difficult to find and debug.
var a = await tm.getChannels();
NOT WORKING -> SyntaxError: await is only valid in async function (huh?)
adding async to getChannels() changes nothing.
Assing async to getChannels() and remove 'await' from assignment returns Promise{undefined} (huh?)
putting async before axios changes nothing as response is already handled by .then()
changing return dict to return await dict gives another "await is only valid in async function" (huh? axios is asynchronous)
I'm scratching my head over this for 2 weeks.
In Swift when something is return in completion handler it is assigned to variable in proper moment, why something returned by Promise not works the same way?
You need to be inside an async function to use the await expression:
The await operator is used to wait for a Promise. It can only be used inside an async function.
await operator on MDN
Example sourced from MDN:
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
Fixing your issue
class TM {
get chListUrl() {
return "http://www.teleman.pl/program-tv/stacje";
}
async getChannels() { // you need not use get syntax
let dict = {};
try { // we will be handling possible errors with try catch instead of reject
const response = await axios.get(this.chListUrl);
let $ = cheerio.load(response.data);
let ile_jest_stacji = $('#stations-index a').length;
$('#stations-index a').each( (i,elem) => {
let href = $(elem).attr('href');
let kodstacji = href.replace(/\/program-tv\/stacje\//ig,'');
let nazwastacji = $(elem).text();
dict[nazwastacji]=kodstacji;
});
return dict;
} catch(ex) {
console.log(ex);
return null
}
}
}
// let's make it work!
(async function() {
const tm = new TM()
const channels = await tm.getChannels()
// do whatever you want with channels
console.log(channels)
})()
Now, you're probably not going to call getChannels out of nowhere like this instead you will probably be inside a function that you yourself defined, you need to add the async keyword to this function. Whatever block function your code is in needs to be async.
If you want to use the async/await syntax you should remove the .then() syntax and you can resolve that way:
async getChannels() {
const response = await axios.get(this.chListUrl);
return response
}
You can learn more about async/await in the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Unexpected promise returned in React Native

I am just beginning to work with promises in React and cannot explain why I am returning a promise in a function and not the array I want.
The code is as follows:
async function pullTweets () {
let twitterRest = new TwitterRest(); //create a new instance of TwitterRest Class
var twatts = await twitterRest.pullTimeLine('google'); //pull the Google TimeLine
console.log(twatts);
return twatts;
}
let twitts = pullTweets();
console.log(twitts);
The console.log(twatts); is returning the correct array of tweets; however, the console.log(twitts) is returning a promise.
Any explanation would be greatly appreciated.
Thanks
You need to wait for pullTweets() which is an asynchronous function (that returns a Promise as well) to finish executing.
This can be done by using the keyword await before pullTweets():
let twitts = await pullTweets();
console.log(twitts);
The code you wrote is equivalent to this (using only Promises):
function pullTweets () {
let twitterRest = new TwitterRest();
return twitterRest.pullTimeLine('google').then((twatt) => {
// This logs the array since the promise has resolved successfully
console.log(twatt)
return twatt
})
}
let twitts = pullTweets();
// This logs a pending promise since the promise has not finished resolving
console.log(twitts);

request-promise + co API trigger in protractor test

I want to call module.api.create from my protractor test. Referring this solution:-
Chain multiple Node http request I am using request-promise + co like this:-
//api/module1.js
var co = require('co');
var rp = require('request-promise');
exports.create = co(function* def() {
var response, token;
urlLogin.body.username = username;
response = yield rp(urlLogin);
//extract token and run other APIs
...
}).catch(err => console.log);
And
//api/api.js
var module1= require('./module1'),
exports.module1= function (){
return module1;
};
In my Spec/Test I am adding
api = require('../../api/api');
api.module1.create;
Issue i am facing is than even without calling the "api.module1.create;" line, the require line "api = require('../../api/api');" is calling the create automatically every-time the test is executed
From the co README:
co#4.0.0 has been released, which now relies on promises. It is a stepping stone towards the async/await proposal. The primary API change is how co() is invoked. Before, co returned a "thunk", which you then called with a callback and optional arguments. Now, co() returns a promise.
I believe you're looking for co.wrap, which returns a function that executes the generator and returns a promise (this function may also be known as a thunk). Using just co eagerly executes the generator and returns the result of executing the generator.
const co = require('co')
co(function* () {
// this will run
console.log('hello from plain co!')
})
co.wrap(function* () {
// this won't run because we never call the returned function
console.log('hello from wrapped co 1!')
})
const wrappedfn = co.wrap(function* () {
// this runs because we call the returned function
console.log('hello from wrapped co 2!')
})
wrappedfn()
You can also wrap a function by yourself, which does the same thing as co.wrap and lets you do more stuff afterwards.
exports.create = function() {
return co(function* () {
// this will run only when exports.create is called
console.log('hello from plain co!')
})
// If you want to do stuff after and outside the generator but inside the enclosing function
.then(...)
}

How to translate Promise.try in coffeeScript

Hello I am looking for a code in coffe script which generates this code in javascript
Promise = require('bluebird');
myfunction = function(body) {
return Promise.try(function() {
return console.log('OK');
});
};
I have tried something like:
Promise = require 'bluebird'
myfunction: (body) ->
return Promise.try ->
return console.log('OK')
But the result is something like:
Promise["try"](function() {});
Any idea?? Thanks in advance
I would guess that something is off with the indentation in your file, as the above is correct except:
You don't need return, as the last statement in a function / block is automatically returned.
You should still use = for variable assignment, as opposed to : which is used for assigning properties when defining an object. It's the same in Coffeescript as in Javascript.
This code:
Promise = require 'bluebird'
myfunction = (body) ->
Promise.try ->
console.log 'OK'
Compiles just fine into:
var Promise, myfunction;
Promise = require('bluebird');
myfunction = function(body) {
return Promise["try"](function() {
return console.log('OK');
});
};
Regarding Promise.try -> transpiling into Promise["try"](function …) this is due to try being a reserved keyword in JS.

MochaJS setTimeout ES6

While unit testing my Node.js app, I encountered a problem with Mocha and ES6 while using setTimeout.
Mocha said the test passed, but when I put in something else (to check the test, to make sure it works), it still says it passed, while it should fail.
Code:
describe('.checkToken', function () {
let user = {};
let token = repository.newToken();
it('token has expired', co.wrap(function* () {
setTimeout(function* () {
let result = yield repository.checkToken(user, token.token);
result.body.should.have.property("error");
}, 1000)
}));
});
});
The other tests are all working and there is no problem in that case.
I've already tried an arrow function or a standard function in the callback of setTimeout, but it then crashes on the yield. (Unexpected token)
checkToken is a generator function.
Using:
Nodejs v4.2.1
Co v4.6.0
Should v7.1.0
Mocha v2.3.3
You cannot use setTimeout with a generator. It's the generator that you pass to co.wrap that will be ran asynchronously, and it needs to know about the timeout. You will need to yield the timeout (as something yieldable, like a thunk or a promise):
it('token has expired', co.wrap(function* () {
yield new Promise(resolve => { setTimeout(resolve, 1000); });
let result = yield repository.checkToken(user, token.token);
result.body.should.have.property("error");
}));

Categories

Resources