Reputation: 113
I am having little doubt with how javascript promises are used. I have learned it in a following basic format and it's understandable.
var dopromise = new Promise (function(resolve,reject){
let isclean=true;
if(isclean){
resolve('done');
}
else
{
reject();
}
});
dopromise.then(function(done){
console.log()
}).catch(function(){
console.log()
)}
But I don't understand properly how promises work in below code scenario. Code looks much simpler without details. Have I missed something?
eg
navigator.mediaDevices.getUserMedia({
video: true;
})
.then(function(stream){
alice.addStream(stream);
return alice.createOffer();
})
Upvotes: 0
Views: 98
Reputation: 4445
In very general / (computer) layman terms promises are functions which get executed "asynchrounsly" and therefore when they return any information, there should be some place where you can capture it.
The information returned is captured by a "callback function" called then.
This callback is invoked automatically (by the javascript engine) and "takes a function" as an argument, which is then called again automatically :)
So if I had a piece of code like this
somePromise().then(function() { console.log('2 - Promise returned
something, executing in a separate thread') });
console.log('1 - This is executed in the main thread');
The output would technically be:
1 - This is executed in the main thread
2 - Promise returned something executing in a separate thread
Because the promise can take a long time to return depending on how much work it is doing and you don't want the main thread to wait that long.
Upvotes: -2
Reputation: 83527
The syntax is the same. Whatever is before .then()
must produce a Promise
. In your case, you created the Promise
explicitly. In the case of
navigator.mediaDevices.getUserMedia({
video: true;
})
getUserMedia()
takes an object as a parameter and returns a Promise
.
The rest is not legal JavaScript syntax as far as I know. You can either do
.then(function(stream){
alice.addStream(stream);
return alice.createOffer();
})
or with ES6
.then((stream) => {
alice.addStream(stream);
return alice.createOffer();
})
Upvotes: 1
Reputation: 190945
getUserMedia
returns an already created Promise
. In your first example you are manually creating a Promise
in order to make something asynchronous.
Upvotes: 4