I create two promises, but I do not run the then method on those promises. Yet once the promise objects go out of scope, the promise code runs as if .then was called.
How is a Promise settled without a call to the .then method?
I am asking because I would like to load an array with Promise objects and then run the promises in sequence.
function promises_createThenRun() {
const p1 = createPromise1();
const p2 = createPromise2();
console.log('before hello');
alert('hello');
console.log('after hello');
// the two promises run at this point. What makes them run?
}
function createPromise1() {
let p1 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 1');
resolve();
}, 2000);
});
return p1;
}
function createPromise2() {
let p2 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 2');
resolve();
}, 1000);
});
return p2;
}
The code inside the Promise constructor runs when the promise is created and it runs synchronously which surprises some people. So even without then() everything still runs.
new Promise(resolve => console.log("running"))
Code in the callback for the setTimeout however, doesn't run until it's called, but it too will run even without the then()
new Promise(resolve => {
console.log("promise created")
setTimeout(() => console.log("this runs later"), 1000)
})
When calling .then you just set up a "callback" which says what should happen after the promise is done. So the promise will be called, with or without declaring such callback.
Imagine the promise that calls a AJAX request. Calling .then and passing a function to it will make it run when the ajax call was finished (successfully or not as in timeout or other errors). But not calling .then will not stop the request to be run. You will simply not react to the results of the request.
I thought, that "Promises won't run" if you don't call then/catch/finally on them, too. But if you consider, that these methods return new Promises, and according to your logic, you need to call then/catch/finally on these returned Promises in order to "run" them, you'll be stuck in an infinite loop)))
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');
I have this function:
export async function promisePlay(example: someInterface): Promise<string> {
const data = await fetch(example.url)
return new Promise((resolve, reject) => {
resolve("Lets test this")
console.log("This point shouldnt be reached");
})
}
When I run this I'm seeing the text This point shouldnt be reached in the console output. What I want (and thought) was that the resolve() should return and stop from running further.
Could someone please tell me what I'm fundamentally misunderstanding and how to correct?
Thanks.
resolve is a function in a variable.
You are calling the resolve function and passing the return value of the promise as the parameter.
However, that does not stop execution or break out.
If you want to exit the function, you must use return;.
Calling resolve does stop the pending await command of wherever you called the original function.
Whatever you value you pass to return will not be passed to the variable that resolves the promise and it will not stop the pending promise in the await command.
function test(yourWord)
{
return new Promise((resolve, reject) =>
{
// This will allow the command
// let res = await test("hello");
// to continue executing. It will stop executing on that line
// unless you call resolve or reject
resolve("you said: " + yourWord);
// this will continue to execute
console.log("I'm still alive");
// this string return value will be ignored
return "blah blah";
// this will not be executed since the function has returned
console.log("I'm dead");
});
}
(async () =>
{
// this will pause execution until resolve or reject is called and
// whatever value is passed into resolve() will be assigned to res
let res = await test("hello");
// this will echo out "you said hello"
console.log("res: " + res);
})();
You can return the resolve
export async function promisePlay(example: someInterface): Promise<string> {
const data = await fetch(example.url)
return new Promise((resolve, reject) => {
return resolve("Lets test this")
console.log("This point shouldnt be reached");
})
}
Promise body is synchronous, when you resolve the promise, it won't return(stop executing further statements).
I think you are confused between promises resolve and returning from them.
Consider below example,
new Promise((resolve) => {
console.log("inside promise");
resolve("promise resolved");
console.log("after resolving");
}).then(val => console.log(val));
In the above snippet, the console will print inside promise then after removing. It means it will execute all the statement in the promise first then it will wait for the promise to resolve. If you don't want to execute any statement further resolve, you can add return resolve in the function, cause its a normal function anyhow.
A JS promise has 3 states initial, fulfilled and rejected.
When awaiting a promise, the code waits for the state to change from initial to either rejected or resolved before execution continues.
When you await your promisePlay() function, execution will continue after the await as soon as reject() or resolve() is called.
Your case is special because you have code after you have resolved() within your promise.
It appears that during some experimentation of my own, it appears the JS engine waits until all the code is executed after the resolve(), I suppose its a bad idea to rely on this behaviour, as other answers suggest perhaps you should be return the result you want within in the resolve
I am new to JS and was learning promises. So, let's say we have this code:
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) { // (**)
alert(result); // 1
return result * 2;
})
As you can see the code above, when promise is invoked, setTimeout is run via callback queue. The question is When setTimeOut is sent to a browser, will JS engine omit .then() and continues running the rest of the code until the promise resolves? Secondly, async/await example:
async function showAvatar() {
// read our JSON
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
// read github user
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
// show the avatar
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
// wait 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
showAvatar();
When showAvatar function is called, JS engine will encounter let response = await fetch('/article/promise-chaining/user.json'); and sends fetch to the browser to handle. The second question is Will JS engine wait until fetch gets resolved or Will JS engine continue executing let user = await response.json(); and the rest of the code inside showAvatar function? If so, how can JS engine handle response.json() since response is not received? Hope you got my point))).
Your first example works like this:
new Promise runs, calling the function you pass it (the executor function) synchronously
Code in the executor function calls setTimeout, passing in a function to call 1000ms later; the browser adds that to its list of pending timer callbacks
new Promise returns the promise
then is called, adding the function you pass into it to the promise's list of fulfillment handlers and creating a new promise (which your code doesn't use, so it gets thrown away).
1000ms or so later, the browser queues a call to the setTimeout callback, which the JavaScript engine picks up and runs
The callback calls the resolve function to fulfill the promise with the value 1
That triggers the promise's fulfillment handlers (asynchronously, but it doesn't really matter for this example), so the handler attached in Step 4 gets called, showing the alert and then returning result * 2 (which is 1 * 2, which is 1). That value is used to fulfill the promise created and thrown away in Step 4.
Will JS engine wait until fetch gets resolved or Will JS engine continue executing let user = await response.json();...
It waits. The async function is suspended at the await in await fetch(/*...*/), waiting for the promise fetch returned to settle. While it's suspended, the main JavaScript thread can do other things. Later, when the promise settles, the function is resumed and either the fulfillment value is assigned to response (if the promise is fulfilled) or an exception will get thrown (if it is rejected).
More generally: async functions are synchronous up until the first await or return in their code. At that point, they return their promise, which is settled later based on the remainder of the async function's code.
In a comment you asked:
when async function is suspended at each await, will async function is removed from the call stack and is put back to the call stack again when the promise being awaited settles?
At a low level, yes; but to make debugging easier, a good, up-to-date JavaScript engine maintains an "async call stack" they use for error traces and such. For instance, if you run this on Chrome...
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function inner() {
await delay(80);
throw new Error("boom");
}
async function outer() {
await inner();
}
function wrapper() {
outer()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error.stack);
});
}
wrapper();
...the stack looks like this:
Error: boom
at inner (https://stacksnippets.net/js:18:11)
at async outer (https://stacksnippets.net/js:22:5)
Notice the "async" prior to "outer," and also notice that wrapper isn't mentioned anywhere. wrapper is done and has returned, but the async functions were suspended and resumed.
I have lot of confusion in promise. It's a synchronous or asynchronous ?
return new Promise (function(resolved,reject){
//sync or async?
});
The function you pass into the Promise constructor runs synchronously, but anything that depends on its resolution will be called asynchronously. Even if the promise resolves immediately, any handlers will execute asynchronously (similar to when you setTimeout(fn, 0)) - the main thread runs to the end first.
This is true no matter your Javascript environment - no matter whether you're in Node or a browser.
console.log('start');
const myProm = new Promise(function(resolve, reject) {
console.log('running');
resolve();
});
myProm.then(() => console.log('resolved'));
console.log('end of main block');
Promises aren't exactly synchronous or asynchronous in and of themselves. When you create a promise the callback you pass to it is immediately executed and no other code can run until that function yields. Consider the following example:
new Promise(function(resolve, reject) {
console.log('foo');
})
console.log('bar');
The code outside the promise has to wait for the code inside the promise (which is synchronous) to complete before it can begin execution.
That said, promises are a common way of dealing with asynchronous code. The most common use case for a promise is to represent some value that's being generated or fetched in an asynchronous fashion. Logic that depends on that value can asynchronously wait until the value is available by registering a callback with .then() or related Promise methods.
This code makes it clearer:
console.log("0");
new Promise((resolve, reject) => {
console.log("1");
resolve();
}).then(() => {
console.log("2");
});
console.log("3");
The code prints: 0 1 3 2
So, then runs asynchronously while the main call back function runs synchronously.
I don't find other answers are accurate.
new Promise (executor_function)
executor_function here will run immediately as part of Promise initialization --- this means Promise init will be executed synchronously, but does not mean code inside executor_function will necessarily run synchronously, instead, code inside executor_function can also be run asynchronously, for example:
new Promise ((resolve, reject) => {
setTimeout(resolve, 1000); // wait 1s
})
When you create a promise and pass a call back to it
that callback is gonna executed immediately (sync)
const promise= new Promise(function(resolve, reject) {
//doing some logic it gonna be executed synchronously
console.log("result");
})
console.log("global log")
But when you resolve it by .then() method it will act in asynchronous way
so for example :
const promise = new Promise(function(resolve, reject) {
//doing some logic it gonna be executed synchronously
resolve("fullfiled")
})
promise.then(v => {
console.log(v)
})
console.log("global log")
Promises are like normal classes in Javascript. Assume you are creating your own Promise implementation, your promise class would roughly look like this. Notice in your constructor you are expecting a method to be passed that you call immediately passing resolve and reject as parameters.
class Promise {
constructor(method) {
method(resolve, reject)
}
resolve() { ... }
reject() { ... }
then() { ... }
}
So when you do new Promise(), you are just creating a new object. Your Promise constructor will run, and it will call the method immediately. So that is why the code inside your promise gets executed synchronously.
return new Promise (function(resolved,reject){
//sync or async?
});
If inside your function you were calling another function that was async in nature, then that another function would get executed asynchronously, otherwise, everything else gets executed synchronously.
If you had chains in promise using then, then it only gets called after your first promise has called resolve().
return new Promise (function(resolve,reject){
const a = 5*5; // sync operation.
db.save(a, function callback() { // async operation.
resolve() // tells promise to execute `then` block.
});
});
const promise = new Promise(function(resolve, reject) {
//doing some logic it gonna be executed synchronously
console.log("check")
resolve("fullfiled")
})
promise.then(v => {
console.log(v)
})
console.log("global log")
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');