Can I do a "lazy" promise with Bluebird.js? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want a construct similar to promise that waits until then is called before it runs. That is, if I never actually call then, the promise will never run.
Is this possible?

Make a function which creates and returns a promise on first invocation, but returns the same promise on each subsequent invocation:
function getResults() {
if (getResults.results) return getResults.results;
getResults.results = $.ajax(...); # or where ever your promise is being built
return getResults.results;
}
Promises don't work in such a way that they could support lazy loading. Promises are created by asynchronous code in order to communicate a result. Until the async code has been invoked, there simply is no promise.
You could certainly write a promise-like object which did lazy invocation, but code that generated these promises would be very different:
// Accepts the promise-returning function as an argument
LazyPromise = function (fn) {
this.promise = null;
this.fn = fn
}
LazyPromise.prototype.then = function () {
this.promise = this.promise || fn();
this.promise.then.apply(this.promise, arguments)
}
// Instead of this...
var promise = fn();
// You'd use this:
var promise = new LazyPromise(fn);
It's better in this uncommon use to make the actual creation of the promise lazy (as in either above example), rather than trying to make promises themselves responsible for lazy-evaluation.

Related

What this piece of JS code is doing exactly [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
This is sample code from here
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
I have few questions:
What is the resolve in the Promise constructor, and what resolve(x) do exactly?
What is asynchronous code? is it the call to resolveAfter2Seconds or just the code inside resolveAfter2Seconds (that is: the promise execution, while resolveAfter2Seconds returns immediately?
What is the resolve in the Promise constructor, and what resolve(x) do exactly?
The Promise constructor takes a callback function called executor. That executor callback will be called with two parameters. This call is made by the constructor itself. Both of parameters that will be passed in are functions:
resolve - when called will fulfill* the promise, marking it as successfully completed. The argument passed to the resolve function will become the value for that promise.
The value for the promise will be passed to .then() callback. If the promise is awaited the result is the value of the promise.
reject - when called will reject the promise, marking it as unsuccessfully completed. The argument passed to the reject function will become the reason that promise was rejected.
The reason for the rejection will be passed to .catch() callback. If the promise is awaited the reason is thrown and can be caught in a try/catch block.
Quick note: as with all parameters, these two can be given any name. The resolve and reject are very common ways of naming the functions.
* not necessarily true if passing another promise. If a another promise is passed, the current promise will adopt that promise's completion state. So, if resolve is called with a promise that is later rejected, the current promise will also be rejected.
The executor is then called immediately and the promise will be pending until either resolve or reject is called.
In your case the executor is:
resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
}
Which means that resolve is going to be called 2 seconds later with the value for x making that the value for the promise.
The await will suspend the execution of f1() and resume it when promise returned by resolveAfter2Seconds(10) settles. The result of await resolveAfter2Seconds(10) is the value of the promise. Which is 10 as you can see in the log.
What is asynchronous code? is it the call to resolveAfter2Seconds or just the code inside resolveAfter2Seconds (that is: the promise execution, while resolveAfter2Seconds returns immediately?
I would say that for practical purposes, asynchronous code is anything that will finish later than the normal top-to-bottom execution of code:
console.log(1);
console.log(2);
console.log(3);
async function later(x) { return x; }
console.log(1);
later(2).then(value => console.log(value));
console.log(3);
You could definitely try to make an argument otherwise, however trying to pinpoint exactly where async code starts and ends is not very useful. It runs the risk of turning into something that resembles Sorites paradox. If fn1 is not async code, then is it calling fn2 which lies inside? Or is it fn3 which is inside fn2? Etc. Hence my proposed more practical solution. If a function causes some effect to come up later than the current run-to-completion cycle we can say that it is asynchronous. So, any function that returns a promise (which includes all async functions) are asynchronous.
You can also see my answer here which discusses various asynchronous functions more.
Further reading:
What is the correct terminology for javascript promises - very important as it explains the fundamental concept of promises.
`resolve` and `reject` functions inside a Promise's executor
How is a promise/defer library implemented?
Concept - Distilling how a promise works?

Which is better Await Vs Then for NodeJs Promise? and How Await works [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Hi I just started nodejs, I read some articles for async functions. There are some something really confused me, I hope to get some explanation or recommended materials here.
I know in async function, we can resolve a promise using then, also we can use 'await' to wait for promise resolved. Which is better? or are they same mechanism?
Actually, I use multiple await in my nodejs async function, for my understanding, await will stop the script and wait. This is sound like a synchronous function, right? So why do we need await? Is this a good way to do coding in Node?
I call these async functions in angularJS(using promise.then()) to get result. How does it works? I mean, what will I happened when angular call node function, how do them communicate?
If any unclear please comment.
Thank you so much
An async function, always return a pending Promise that will be resolved with the value returned by the function (so the function runs asynchronously)
Using await, the current function is suspended until the promise associated with the await is resolved (so the javascript below an await is transformed to a then() of the awaited promise)
Using then(), you stay in the function after declaring the promise, meaning that you can start multiple promises in parallel.
await is interesting because it simplifies the code when you have to wait for the result before continuing the function, like using a then for rest of the function.
Because await suspends the code, everything below an await is deferred, including any new promise.
So if you want to start all the promises in backgound, you must declare and store them into variables before using any await, like this:
var p1 = new Promise(...)
var p2 = new Promise(...)
try {
let r1 = await p1;
let r2 = await p2;
} catch (e) {}

Promises - difference between passing resolve function and wrapper function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have Node.js application. Why these two code fragments do not work in the same way?
1)
function myFn1() {
return new Promise(function(resolve, reject) {
myFn2().then(function(url) {
resolve(url);
});
});
}
2)
function myFn1() {
return new Promise(function(resolve, reject) {
myFn2().then(resolve);
});
}
Common:
function myFn2() {
return new Promise(function(resolve, reject) {
var url = 'example.com';
resolve(url);
});
}
I call it with
myFn1().then(function(url) {
console.log(url);
});
With code 1) url is passed properly, but with code 2) url is undefined.
Do I not pass one-argument function in both cases? What is the difference?
First off, avoid the promise anti-pattern. When you already have a promise, just use it and return it. Don't wrap it in a new promise. Besides being inefficient, it's real easy to make mistakes, particularly with error handling (which you have).
So, what you should be doing is this:
function myFn1() {
return myFn2().then(function(url) {
// do some modification to url and then return that
// or some other processing here
return url;
});
}
There is simply no need to wrap the returned promise from myFn2() in another promise. In your specific case when doing so, you silently ate any errors from that inner promise and they were not propagated to the caller of myFn1() which is nearly always a bug, sometimes a very serious bug.
And, if you really have nothing to do inside the .then() handler, then you don't even need it either:
function myFn1() {
// some code here
return myFn2();
}
As to the original question, your two code fragments 1) and 2) work the same way and have no meaningful behavior differences other than one makes an extra function call and uses a little more stack to do so.
When you do this:
myFn2().then(resolve);
You're telling .then() to call resolve with whatever argument would normally be passed to the .then() handler. Since that argument in your case is url, then:
.then(resolve);
is exactly the same as:
.then(function(url) {
resolve(url);
});
They both call resolve with exactly the same argument. The first is a shorthand and should be used when the argument that .then() will use for it's callback is exactly the argument you want to your function. The second should be used if the arguments for your function are not exactly the same or, obviously, if you have more than a single function call to do in the .then() handler. So, if you wanted to add a ".jpg" extension to the URL before calling resolve, then you'd have to do:
.then(function(url) {
resolve(url + ".jpg");
});
With code 1) url is passed properly, but with code 2) url is
undefined. Do I not pass one-argument function in both cases? What is
the difference?
Assuming the promise returned by myFn2() resolves to url, then there should be no difference between your scenario #1 and #2. The promise returned by myFn1() should resolve to the same value either way.
Now, if you put some code in a .then() handler and forget to return the desired value from that .then() handler, then the resolved value of the promise becomes undefined which may be what is happening in your real code. So, if you do this:
function myFn1() {
return myFn2().then(function(url) {
console.log(url);
});
}
myFn1().then(function(url) {
console.log(url); // will be undefined
})
Because you didn't return anything from the .then() handler inside of myFn1. That means the return value is undefined so the promise took on that return value. Just remember, if you want your promise to have a specific resolved value, you have to return it from any .then() handlers in the chain.
function myFn1() {
return myFn2().then(function(url) {
console.log(url);
return url; // make sure the promise retains this resolved value
});
}

How can we use promise in node.js packages [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When we write a module for node.js, we use callback functions. I learned promises in javascript and I want to use in node.js module. Can we use promises instead of callback functions ? if we can, how ?
note : via function in node module file ( you know exports.some_func ) , we do somethings and we can send back informations with callback . Can we use promise instead of that callback ?
Can we use promise instead of that callback ?
Yes, rather than accepting a callback in your exported function, you can just return a promise and make sure that promise is resolved/rejected with the proper value/reason when the async operation is done.
Here's an example:
Imagine you have a module interface for reading a file, then you can have that interface return a promise like this:
// myFileModule.js
const fs = require('fs');
module.exports.getFile = function(filename, options) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, options, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
The caller would then use it like this:
const myFiles = require('myFileModule.js');
myFiles.getFile('temp.txt').then(function(data) {
// process data here
}, function(err) {
// got an error here
});

What is the use of the .then function in javascript? [duplicate]

This question already has answers here:
jQuery deferreds and promises - .then() vs .done()
(11 answers)
Closed 7 years ago.
There is not much answer for this simple question that I have. My main question is that I have seen the .then method used a lot in JavaScript and I know the main thing where randomobject.then(//This returns success, //this returns failure). But there are things that I don't get such as the code here:
var success = function (response) {
return response.data;
};
var error = function (errResponse) {
$log.error(errResponse.data.Message);
};
function getsomeData() {
var url = baseUrl + 'api/somedata';
return $http.get(url).then(success, error);
}
First off in that code I'm wondering how the var success knows what data it is getting and the same with error. It says response.data but what is response? It's probably the result of the http.get but that doesn't make much sense code wise. Also it seems that when I have a function for example.
getsomeData returns what it returns. Why doesn't it work if I do the ff:
var dataHolder = randomAngularService.getsomeData()
it returns an object that holds a data under $$state but somehow the .then makes it work if you do the ff:
randomAngularService.getsomeData().then(function (response) {
if(response != null) {
console.log('got the data');
$scope.meeData = response;
}
});
I thought the .then only takes two parameters? This is what's confusing me.
Also is the .then property a JavaScript method or a jQuery one?
It's used to replace (or provide an alternate way) the old callback mechanism with a cleaner way to handle asynchronous requests, instead of passing your callbacks as parameters, you can chain your function with .then, given function will be executed once the promise gets resolved.
Anyhow, this is just a basic explanation, you should really get into the books of promises for more info.
I'm lazy to explain the whole promise thing, but just to answer question about .then
The 2 arguments inside .then actually means "call this function when the promise is resolved(success)/rejected(failed)"
About the arguments inside the functions, they should be specified in the API, because the caller (for instance $http.get) get to decide what to pass when calling that function.

Categories

Resources