This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 6 years ago.
Why when a promise chain has an error it will not execute .then unless the .then references an external method with a parameter?
So this example I purposely throw an error in the promise chain. The first three .then's do not fire, as expected. However, the last .then that has a method with a parameter, fires. Why? And then the .catch fires, as expected.
var Promise = require('bluebird');
var testVar = 'foo';
errorOnPurpose()
.then(function() {
console.log('This will not fire, as expected');
})
.then(function(testVar) {
console.log('This also will not fire, as expected');
})
.then(testMethod1)
.then(testMethod2(testVar))
.catch(function(error) {
console.log('Error:::', error, ' , as expected');
});
function errorOnPurpose() {
return new Promise(function(resolve, reject) {
return reject('This promise returns a rejection');
});
}
function testMethod1() {
console.log('This one will not fire either, as expected');
}
function testMethod2(foo) {
console.log('This will fire!!!!, ARE YOU KIDDING ME!! WHY??');
}
Results in the console:
This will fire!!!!, ARE YOU KIDDING ME!! WHY??
Error::: This promise returns a rejection , as expected
.then(testMethod2(testVar)) In this method you are not passing the testMethod2 function to then, you are passing its response (Because in Javascript you call a function by writing funcName(funcParam))
to pass the function with some parameters you have to call it like this:
.then(testMethod2.bind(this, testVar))
Function.prototype.bind
This has nothing to do with promises.
You are invoking the method immediately: testMethod2(testVar)
Then you are passing the return value of that method invocation to then.
Related
I am trying to wrap my head around promise object in JavaScript. So here I have this little piece of code. I have a promise object and two console.log() on either side of the promise object. I thought it would print
hi
There!
zami
but it printed
hi
zami
There!
Why it is like that? I have zero understanding on how promise works, but I understand how asynchronous callback works in JavaScript. Can any one shed some light on this topic?
console.log('hi');
var myPromise = new Promise(function (resolve, reject) {
if (true) {
resolve('There!');
} else {
reject('Aww, didn\'t work.');
}
});
myPromise.then(function (result) {
// Resolve callback.
console.log(result);
}, function (result) {
// Reject callback.
console.error(result);
});
console.log('zami');
Summary:
A promise in Javascript is an object which represent the eventual completion or failure of an asynchronous operation. Promises represent a proxy for a value which are getting in some point in the future.
A promise can have 3 states which are the following:
Pending: This is the initial state of the promise, the promise is now waiting for either to be resolved or rejected. For example, when are reaching out to the web with an AJAX request and wrapping the request in a promise. Then the promise will be pending in the time window in which the request is not returned.
Fulfilled: When the operation is completed succesfully, the promise is fulfilled. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are succesfully getting data back the promise is said to be fulfilled.
Rejected: When the operation has failed, the promise is rejected. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are getting a 404 error the promise has been rejected.
Promise Constructor:
We can create a promise in the following manner:
let prom = new Promise((res, rej) => {
console.log('synchronously executed');
if (Math.random() > 0.5) {
res('Success');
} else {
rej('Error');
}
})
prom.then((val) => {
console.log('asynchronously executed: ' + val);
}).catch((err) => {
console.log('asynchronously executed: ' + err);
}).finally(() => {
console.log('promise done executing');
});
console.log('last log');
Points of interest:
The code inside the promise constructor is synchronously executed.
then method takes as a first argument a callback which is asynchronously executed on promise fulfillment.
then method takes as a second argument a callback which is asynchronously executed on promise rejection. However we are usually using the catch method for this (because this is more verbose), which also takes a callback which is asynchronously executed on promise rejection. catch is essentially the same as then(null, failCallback).
The then callback receives as a first argument the resolved value (the string 'success' in this case).
The catch callback receives as a first argument the rejected value (the string 'Error' in this case).
The finally method receives a callback which is executed on both promise fulfillment and rejection. Here we can write 'cleanup' code which need to be executed always regardless of promise outcome.
Your example:
In your code 'Zami' was printed before 'there' because the log which logged 'there' was in a then callback function. We earlier pointed out that these callbacks are executed asynchronously and thus will be executed last.
Promise execution is asynchronous, which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code.
Basically, your code is doing the following:
Log 'Hi'
Create a promise
Execute the promise
Log 'zami'
Promise is resolved and logs 'There'.
If you want it to print 'Hi there, zami', you will have to
myPromise.then(function (result) {
// Resolve callback.
console.log(result);
console.log('zami');
}, function (result) {
// Reject callback.
console.error(result);
});
Even though you resolved the promised synchronously, the handlers you pass into then get called asynchronously. This is according to the defined specification:
onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack
I would recommend you to understand how event loop works in JavaScript.
take time and watch this Video.
It will clear your doubts.
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Below is the example of promise:
const post = new Promise((resolve, reject) => {
resolve("Appended from getPostWithPromise()");
});
const getPostWithPromise = function () {
post
.then(function (fulfilled) {
$("body").append("<div>" + fulfilled + "</div>");
})
.catch(function (error) {
console.log(error);
});
}
function getPostWithoutPromise() {
$("body").append("<div>Appended from getPostWithoutPromise()</div>");
}
$(function () {
getPostWithPromise(); // this will print last
getPostWithoutPromise(); // this will print first
$("body").append("<div>Appended directly</div>"); // second
});
you can test it => JavaScript Promises example
for detail understanding you can read this post => https://scotch.io/tutorials/javascript-promises-for-dummies
Promise:
new Promise((resolve, reject) => {
resolve(whateverObject)
reject(whateverErrorObject)
})
It is just object that can be chained with then()
You also can make promise! you can return whatever object in that success parameter (resolve) and error parameter (reject)
so very simple concept bro!
Promises are objects.
Each promise object has a then method.
The then method of the promise object accepts a function as a first parameter.
If we call the then method of a promise, the callback function will be executed once the promise gets resolved.
Flow of execution
const promiseObj = new Promise((res, rej) => {
console.log("Promise constructor are synchronously executed");
res("Hii Developer");
})
const callbackFunction = (resolvedValue) => console.log("Resolved Value ", resolvedValue);
promiseObj.then(callbackFunction);
console.log("I am the executed after the constructor");
In the above example, we have created a promise object using the Promise constructor.
The constructor function is synchronously executed.
After creating the promise object, we are calling the then method of the promise object. We have passed a callback function in the first argument of the then method. This callback function will be executed once the promise gets resolved and the stack of the js engine gets empty.
Promise is a object that represents the completion or failure of a event . Promise is a asynchronous thing in JS which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code. So it wont be executed simultaneously. It would take time to either complete or fail for a given task and then execution.
In your Case
log'Hi'.
First your mypromise variable will store a promise object i.e either rejected or resolved(for this, it would take time)
But JS engine will execute further code first then the asynchronous task. SO u will get 'zami'.
once the promise resolved or rejected. It will be called or used wherever it is used in the code. In this case ,it is resolved and log 'there!' in console.
let prom = new Promise((res, rej) => {
console.log('synchronously executed');
if (Math.random() > 0.5) {
res('Success');
} else {
rej('Error');
}
})
prom.then((val) => {
console.log('asynchronously executed: ' + val);
}).catch((err) => {
console.log('asynchronously executed: ' + err);
}).finally(() => {
console.log('promise done executing');
});
console.log('last log');
This question already has answers here:
What's the difference between returning value or Promise.resolve from then()
(6 answers)
Closed 3 years ago.
I was of the understanding that the then() promise method always itself returns a promise. Promises are something I'm still getting used to being a bit of a newb, so I've just been going over some examples and tinkering. The following example shows that the return value of the then method is an object.
const foo = true;
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (foo) {
resolve('Do this');
} else {
reject(Error("Do that"));
}
}, 1500)
})
const bar = myPromise.then(value => value);
console.log(typeof bar); // object
Is this the same as returning a promise? Or do I need to explicitly tell then to return a promise like so (pseudocode, I know not correct) :
.then(value => {
// do something
return new Promise;
})
I want to make sure I've got this. Really appreciate the help.
Yes, The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
And the promise is an object and the typeof promise will be an object. You don't need to explicit return a promise.
You can read more about the promises here
Yeah then() always return a promise. However, the pseudocode is incorrect. The function then takes two arguments:
p.then(onFulfilled[, onRejected]);
p.then(value => {
// fulfillment
}, reason => {
// rejection
});
Exactly like the Promise constructor. Then create a promise from another one. We often omit the onRejected argument because of we handle the reject case with catch.
Here an interesting article: https://medium.com/#kevinyckim33/what-are-promises-in-javascript-f1a5fc5b34bf
And the then doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
Hi I am new to javascript and have recently been learning about promises. I am trying to wait on the result of a network call before moving forward with my logic. To do this I think I need a promise that waits on the network call's result. I have been practicing with promises and noticed some behavior I don't understand.
var mybool = false;
// Promise
var mypromise = new Promise(
function (resolve, reject) {
if (mybool) {
var pvalue = 'PASS';
resolve(pvalue);
} else {
var fvalue = new Error('FAIL');
reject(fvalue);
}
}
);
// call promise
var callpromise = function () {
mypromise
.then(function (fulfilled) {
// yay, you got a new phone
console.log(fulfilled);
})
.catch(function (error) {
// ops, mom don't buy it
console.log(error.message);
});
}
callpromise();
console.log('This will appear first since prev function call is still thinking');
mybool = true;
console.log(mybool);
callpromise();
So as you can see the var mybool determines the output of the promise function. when I run this program this is the output:
"This will appear first since prev function call is still thinking"
true
"FAIL"
"FAIL"
Can someone explain why even after flipping the mybool var the 2ndcallpromise() is still outputting a value I would only expect from mybool = false?
Promises don't get "called", they get created. You create mypromise once, before callpromise gets actually called. By the time, mybool is false. If you want to create a Promise at a specific point in your code, or if you want multiple promises, create the promise inside of a function.
The simplest change to what you're doing is probably to pass mybool into your promise-creator, which as others have pointed out should be a function.
I'm also adding a counter, so that you can see the results which resolve/reject in a different order than their creation.
var mypromise = function(mybool, counter) {
return new Promise(
function (resolve, reject) {
if (mybool) {
var pvalue = 'PASS-' + counter;
resolve(pvalue);
} else {
var fvalue = new Error('FAIL-' + counter);
reject(fvalue);
}
}
)
}
// call promise
var callpromise = function (mybool, counter) {
mypromise(mybool, counter)
.then(function (fulfilled) {
// yay, you got a new phone
console.log(fulfilled);
})
.catch(function (error) {
// ops, mom don't buy it
console.log(error.message);
});
}
callpromise(false, 1);
console.log('This will appear first since prev function call is still thinking');
callpromise(true, 2);
The function ("callback" or "handler" is these are often called) you specify as the first argument to the then function, will be called when the promise "resolves", and the argument to that function (the "callback", not then) is the value you yourself supplied as argument to the resolve call.
Meaning that in your example, fulfilled is "PASS" (the value of pvalue that you specify as argument to resolve). The name fulfilled doesn't seem like a good candidate here, perhaps due to how you understood (incorrectly) promises work. A fitting name for it would be value, or pvalue (the same thing you resolve the promise with).
But the crucial piece of puzzle you're missing is that every time you call then with some callback function, the callback function will execute if the promise is in the "resolved" state (meaning that resolve has already been called earlier).
So you can call then 1000 times, and you will get your callback invoked 1000 times, with that one and the same resolved ("promised" in loose terms) value.
Let's break down your example:
By the time the var mypromise = ...; statement is executed, the mypromise promise is created and resolved -- the Promise constructor immediately invokes the provided function (called "executor" in promise terms), and this executor function in your case immediately calls resolve which puts the promise in the "resolved" state.
callpromise is just a function, which, when executed, essentially causes the user agent to call the function provided as argument to then as soon as and if the mypromise promise is in "resolved" state, which it is already (see 1.)
You call callpromise twice, but the promise was already resolved even before the first call, and so the value of mybool is of absolutely no effect as far as the promised value is concerned -- the promise was already resolved once, and that's it.
Try to add a console.log call in the promise executor function (the one evaluating mybool) and observe how your promise is resolved once, before you even create the callback function.
I am trying to wrap my head around promise object in JavaScript. So here I have this little piece of code. I have a promise object and two console.log() on either side of the promise object. I thought it would print
hi
There!
zami
but it printed
hi
zami
There!
Why it is like that? I have zero understanding on how promise works, but I understand how asynchronous callback works in JavaScript. Can any one shed some light on this topic?
console.log('hi');
var myPromise = new Promise(function (resolve, reject) {
if (true) {
resolve('There!');
} else {
reject('Aww, didn\'t work.');
}
});
myPromise.then(function (result) {
// Resolve callback.
console.log(result);
}, function (result) {
// Reject callback.
console.error(result);
});
console.log('zami');
Summary:
A promise in Javascript is an object which represent the eventual completion or failure of an asynchronous operation. Promises represent a proxy for a value which are getting in some point in the future.
A promise can have 3 states which are the following:
Pending: This is the initial state of the promise, the promise is now waiting for either to be resolved or rejected. For example, when are reaching out to the web with an AJAX request and wrapping the request in a promise. Then the promise will be pending in the time window in which the request is not returned.
Fulfilled: When the operation is completed succesfully, the promise is fulfilled. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are succesfully getting data back the promise is said to be fulfilled.
Rejected: When the operation has failed, the promise is rejected. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are getting a 404 error the promise has been rejected.
Promise Constructor:
We can create a promise in the following manner:
let prom = new Promise((res, rej) => {
console.log('synchronously executed');
if (Math.random() > 0.5) {
res('Success');
} else {
rej('Error');
}
})
prom.then((val) => {
console.log('asynchronously executed: ' + val);
}).catch((err) => {
console.log('asynchronously executed: ' + err);
}).finally(() => {
console.log('promise done executing');
});
console.log('last log');
Points of interest:
The code inside the promise constructor is synchronously executed.
then method takes as a first argument a callback which is asynchronously executed on promise fulfillment.
then method takes as a second argument a callback which is asynchronously executed on promise rejection. However we are usually using the catch method for this (because this is more verbose), which also takes a callback which is asynchronously executed on promise rejection. catch is essentially the same as then(null, failCallback).
The then callback receives as a first argument the resolved value (the string 'success' in this case).
The catch callback receives as a first argument the rejected value (the string 'Error' in this case).
The finally method receives a callback which is executed on both promise fulfillment and rejection. Here we can write 'cleanup' code which need to be executed always regardless of promise outcome.
Your example:
In your code 'Zami' was printed before 'there' because the log which logged 'there' was in a then callback function. We earlier pointed out that these callbacks are executed asynchronously and thus will be executed last.
Promise execution is asynchronous, which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code.
Basically, your code is doing the following:
Log 'Hi'
Create a promise
Execute the promise
Log 'zami'
Promise is resolved and logs 'There'.
If you want it to print 'Hi there, zami', you will have to
myPromise.then(function (result) {
// Resolve callback.
console.log(result);
console.log('zami');
}, function (result) {
// Reject callback.
console.error(result);
});
Even though you resolved the promised synchronously, the handlers you pass into then get called asynchronously. This is according to the defined specification:
onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack
I would recommend you to understand how event loop works in JavaScript.
take time and watch this Video.
It will clear your doubts.
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Below is the example of promise:
const post = new Promise((resolve, reject) => {
resolve("Appended from getPostWithPromise()");
});
const getPostWithPromise = function () {
post
.then(function (fulfilled) {
$("body").append("<div>" + fulfilled + "</div>");
})
.catch(function (error) {
console.log(error);
});
}
function getPostWithoutPromise() {
$("body").append("<div>Appended from getPostWithoutPromise()</div>");
}
$(function () {
getPostWithPromise(); // this will print last
getPostWithoutPromise(); // this will print first
$("body").append("<div>Appended directly</div>"); // second
});
you can test it => JavaScript Promises example
for detail understanding you can read this post => https://scotch.io/tutorials/javascript-promises-for-dummies
Promise:
new Promise((resolve, reject) => {
resolve(whateverObject)
reject(whateverErrorObject)
})
It is just object that can be chained with then()
You also can make promise! you can return whatever object in that success parameter (resolve) and error parameter (reject)
so very simple concept bro!
Promises are objects.
Each promise object has a then method.
The then method of the promise object accepts a function as a first parameter.
If we call the then method of a promise, the callback function will be executed once the promise gets resolved.
Flow of execution
const promiseObj = new Promise((res, rej) => {
console.log("Promise constructor are synchronously executed");
res("Hii Developer");
})
const callbackFunction = (resolvedValue) => console.log("Resolved Value ", resolvedValue);
promiseObj.then(callbackFunction);
console.log("I am the executed after the constructor");
In the above example, we have created a promise object using the Promise constructor.
The constructor function is synchronously executed.
After creating the promise object, we are calling the then method of the promise object. We have passed a callback function in the first argument of the then method. This callback function will be executed once the promise gets resolved and the stack of the js engine gets empty.
Promise is a object that represents the completion or failure of a event . Promise is a asynchronous thing in JS which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code. So it wont be executed simultaneously. It would take time to either complete or fail for a given task and then execution.
In your Case
log'Hi'.
First your mypromise variable will store a promise object i.e either rejected or resolved(for this, it would take time)
But JS engine will execute further code first then the asynchronous task. SO u will get 'zami'.
once the promise resolved or rejected. It will be called or used wherever it is used in the code. In this case ,it is resolved and log 'there!' in console.
let prom = new Promise((res, rej) => {
console.log('synchronously executed');
if (Math.random() > 0.5) {
res('Success');
} else {
rej('Error');
}
})
prom.then((val) => {
console.log('asynchronously executed: ' + val);
}).catch((err) => {
console.log('asynchronously executed: ' + err);
}).finally(() => {
console.log('promise done executing');
});
console.log('last log');
This question already has answers here:
How angular promise .then works
(2 answers)
Closed 7 years ago.
All:
I am pretty new to Promise, just curious how they get resolved, one thing confuse me is:
Some posts show using
var defer = $q.defer();
// some logic block
{
// if success doing something
defer.resolve();
}
return defer.promise;
But if use .then() function, promise is returned from .then(function(){}), I wonder how do I control if this promise resolved or not?
Another confuse is: If I use some chained .then() function, I wonder what is the relationship between them, are they same promise object which is just passed down or each .then will generate a new Promise object and return it?
As specified in this throughout and clear document:
QUESTION 1. I wonder how do I control if this promise resolved or not?
One of the Promise APIs support pecial functions that resolve() or reject() a Promise. So you may use the following functions in your code
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Rejections happen when a promise is explicitly rejected, but also implicitly
if an error is thrown in the constructor callback.
var jsonPromise = new Promise(function(resolve, reject) {
// JSON.parse throws an error if you feed it some
// invalid JSON, so this implicitly rejects:
resolve(JSON.parse("This ain't JSON"));
});
jsonPromise.then(function(data) {
// This never happens:
console.log("It worked!", data);
}).catch(function(err) {
// Instead, this happens:
console.log("It failed!", err);
});
In other variants the Promise is resolved with the return value that is passed to the next link in the chain.
QUESTION 2.
Promises are in some sense functions that will result in the future with some value. The result value is the return value from promise - so basically promise chaining ( .then(...).then... ) are chain of functions that wait till the previous one will end ( resolve with some value ). Then they are called with an argument which is the return value of the last executed function in the queue ( previous link in the chain ).
.then() returns a new promise object thus allowing chaining. (see remark for documentation link)
REMARK
There is great and small description of all Angular promises in official documentation under the section Promise API and next one - Chaining the promises.
This isn't an attempt to explain promises in their full glory - there are blogs for that. This is to answer your specific questions:
Q1:
But if I use .then() function, promise is returned from .then(function(){}), I wonder how do I control if this promise resolved or not?
The resolve handler function of .then controls how this promise is resolved:
If the handler function returns a non-promise value, then the promise with resolve with that value.
var thenPromise = originalPromise.then(function success() {
return "foo";
});
thenPromise.then(function(data){
console.log(data); // "foo"
});
If the handler function returns another promise, then the .then promise will resolve exactly how the new promise would resolve (or reject)
var thenPromise = originalPromise.then(function() {
return $timeout(function(){ return "foo"; }, 1000);
});
thenPromise.then(function(data){
console.log(data); // (after 1 second) "foo"
});
If the handler function throws an exception or if the the return is an explicitly rejected promise `$q.reject:
var thenPromise = originalPromise.then(function() {
return $q.reject("some error");
});
thenPromise.then(function(data){
console.log(data); // doesn't get here
})
.catch(function(err){
console.log(err); // "some error"
});
Q2:
If I use some chained .then() function, I wonder what is the relationship between them, are they same promise object which is just passed down or each .then will generate a new Promise object and return it?
Each .then generates its own promise.
var timeoutPromise = $timeout(afterTimeout, 1000);
var thenPromise = timeoutPromise.then(doSomething);
var anotherThenPromise = timeoutPromise.then(doSomethingElse);
If timeoutPromise resolves, then both doSomething and doSomethingElse would execute and depending on their outcome thenPromise and anotherThenPromise would have their respective resolutions.