const myFirstPromise = new Promise(function (resolve, reject) {
// do something asynch which eventually calls either:
// resolve(someValue); // fulfilled
// or
// reject("failure reason"); // rejected
});
The
executor function is executed immediately by the Promise implementation, passing
resolve and
reject functions (the executor is called before the Promise constructor even returns the created object); the resolve and reject functions are provided by the Javascript engine. The resolve and reject functions, when called, resolve or reject the promise, respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred.
If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.
Getting the returned result from a Promise
- Promises can not return anything, they just pass results to callbacks (which are specified with .then())
- Without .then() you can not get the returned result from the Promise!
const p = new Promise(function(resolve,reject) {
// the asynchronous work - just a console.log()
console.log("Doing some work...");
resolve("Done");
});
// we assume the Promise p is always resolved
p.then(function(result) {
console.log(result); // just print the returned result of the Promise
})
Web Workers
- allow running js code in the background threads of the browser
- a worker communicates with the code that created it through message passing
var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.