I want to extend native Javascript Promise class with ES6 syntax, and be able to call some asynchronous function inside the subclass constructor. Based on async function result the promise must be either rejected or resolved.
However, two strange things happen when then function is called:
subclass constructor is executed twice
"Uncaught TypeError: Promise resolve or reject function is not callable" error is thrown
class MyPromise extends Promise {
constructor(name) {
super((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
this.name = name
}
}
new MyPromise('p1')
.then(result => {
console.log('resolved, result: ', result)
})
.catch(err => {
console.error('err: ', err)
})
The reasoning is simple but not necessarily self evident.
.then() returns a promise
if then is called on a subclass of Promise, the returned promise is an instance of the subclass, not Promise itself.
the then returned promise is constructed by calling the subclass constructor, and passing it an internal executor function that records the value of resolve and reject arguments passed to it for later use.
"later use" covers resolving or rejecting the promise returned by then asynchronously when monitoring execution of onfulfilled or onrejected handlers (later) to see if they return a value (which resolves the then returned promise) or throw an error (which rejects the promise).
In short then calls internally obtain and record references to the resolve and reject functions of promises they return.
So regarding the question,
new MyPromise( 'p1')
works fine and is the first call to the subclass constructor.
.then( someFunction)
records someFunction in a list of then calls made on new MyPromise (recall then can be called multiple times) and attempts to create a return promise by calling
new MyPromise( (resolve, reject) => ... /* store resolve reject references */
This is the second call to the subclass constructor coming from then code. The constructor is expected to (and does) return synchronously.
On return from creating the promise to return, the .then method makes an integrity check to see if the resolve and reject functions it needs for later use are in fact functions. They should have been stored (in a list) along with callbacks provided in the then call.
In the case of MyPromise they are not. The executor passed by then, to MyPromise, is not even called. So then method code throws a type error "Promise resolve or reject function is not callable" - it has no means of resolving or rejecting the promise it is supposed to return.
When creating a subclass of Promise, the subclass constructor must take an executor function as its first argument, and call the executor with real resolve and reject functional arguments. This is internally required by then method code.
Doing something intricate with MyPromise, perhaps checking the first parameter to see if it is a function and calling it as an executor if it is, may be feasible but is outside the scope of this answer! For the code shown, writing a factory/library function may be simpler:
function namedDelay(name, delay=1000, value=1) {
var promise = new Promise( (resolve,reject) => {
setTimeout(() => {
resolve(value)
}, delay)
}
);
promise.name = name;
return promise;
}
namedDelay( 'p1')
.then(result => {
console.log('fulfilled, result: ', result)
})
.catch(err => {
console.error('err: ', err)
})
;TLDR
The class extension to Promise is not an extension. If it were it would need to implement the Promise interface and take an executor function as first parameter. You could use a factory function to return a Promise which is resolved asynchronously (as above), or hack the posted code with
MyPromise.prototype.constructor = Promise
which causes .then to return a regular Promise object. The hack itself refutes the idea that a class extension is taking place.
Promise Extension Example
The following example shows a basic Promise extension that adds properties supplied to the constructor. Of note:
The Symbol.toString getter only affects the output of converting an instance to a string. It does not change "Promise" to "MyPromise" when logging an instance object on browser consoles tested.
Firefox 89 (Proton) is not reporting own properties of extended instances while Chrome does - the reason test code below logs instance properties by name.
class MyPromise extends Promise {
constructor(exec, props) {
if( typeof exec != "function") {
throw TypeError( "new MyPromise(executor, props): an executor function is required");
}
super((resolve, reject) => exec(resolve,reject));
if( props) {
Object.assign( this, props);
}
}
get [Symbol.toStringTag]() {
return 'MyPromise';
}
}
// Test the extension:
const p1 = new MyPromise( (resolve, reject) =>
resolve(42),
{id: "p1", bark: ()=>console.log("woof") });
console.log( "p1 is a %s object", p1.constructor.name);
console.log( "p1.toString() = %s", p1.toString());
console.log( "p1.id = '%s'", p1.id);
console.log( "p1 says:"); p1.bark();
const pThen = p1.then(data=>data);
console.log( "p1.then() returns a %s object", pThen.constructor.name);
let pAll = MyPromise.all([Promise.resolve(39)]);
console.log( "MyPromise.all returns a %s object", pAll.constructor.name);
try { new MyPromise(); }
catch(err) {
console.log( "new MyPromise() threw: '%s'", err.message);
}
The best way I found to extend a promise is
class MyPromise extends Promise {
constructor(name) {
// needed for MyPromise.race/all ecc
if(name instanceof Function){
return super(name)
}
super((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
this.name = name
}
// you can also use Symbol.species in order to
// return a Promise for then/catch/finally
static get [Symbol.species]() {
return Promise;
}
// Promise overrides his Symbol.toStringTag
get [Symbol.toStringTag]() {
return 'MyPromise';
}
}
new MyPromise('p1')
.then(result => {
console.log('resolved, result: ', result)
})
.catch(err => {
console.error('err: ', err)
})
The post by asdru contains the correct answer, but also contains an approach (constructor hack) that should be discouraged.
The constructor hack checks if the constructor argument is a function. This is not the way to go as the ECMAScript design contains a specific mechanism for sub-classing Promises via Symbol.species.
asdru's comment on using Symbol.species is correct. See the explanation in the current ECMAScript specification:
Promise prototype methods normally use their this value's constructor
to create a derived object. However, a subclass constructor may
over-ride that default behaviour by redefining its ##species property.
The specification (indirectly) refers to this note in the sections on finally and then (look for mentions of SpeciesConstructor).
By returning Promise as the species constructor, the problems that traktor's answer analyzes so clearly are avoided. then calls the Promise constructor, but not the sub-classed MyPromise constructor. The MyPromise constructor is called only once with the name argument and no further argument-checking logic is needed or appropriate.
Therefore, the code should simply be:
class MyPromise extends Promise {
constructor(name) {
super((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
this.name = name
}
static get [Symbol.species]() {
return Promise;
}
get [Symbol.toStringTag]() {
return 'MyPromise';
}
}
Less is more!
Some notes:
MDN has an example for the use of the species symbol in extending Array.
The most recent browser versions (Chrome, FF, Safari, Edge on MAC and Linux) handle this correctly, but I have no information on other browsers or legacy versions.
Symbol.toStringTag is a very nice touch, but not required. Most browsers use the value returned for this symbol to identify the sub-classed promise in the console, but, beware, FF does not - this could easily be confusing. In all browsers, however, new MyPromise('mine').toString() yields "[object MyPromise]".
All of this is also unproblematic if you author in Typescript.
As noseratio points out, a primary use-case for extending Promises is the wrapping of (legacy) APIs that support abort or cancel logic (FileReader, fetch, ...).
You have to make it thenable by implementing the then method.
Otherwise, that of the superclass, Promise, will be called, and it’ll try to create another Promise with your MyPromise’ constructor, which is not compatible with the original Promise constructor.
The thing is, it’s tricky to properly implement the then method that works just like Promise’s does. You’ll likely end up having an instance of Promise as a member, not as a superclass.
Summarizing the above into a short tl;dr for those who just want to get something working and move on, you just need to add this to your class body:
static get [Symbol.species]() {
return Promise;
}
A full TypeScript example:
class MyPromise extends Promise<string> {
constructor(name: string) {
super((resolve) => {
setTimeout(() => {
resolve(name)
}, 1000)
})
this.name = name;
}
static get [Symbol.species]() {
return Promise;
}
}
const p = new MyPromise('hi');
p.name === 'hi'
const x: string = await p;
x === 'hi'
That's all you need.
Forgoing Symbol.toStringTag may make MyPromise just look like a Promise in some debugging contexts, and you won't be able to do MyPromise.race or MyPromise.all, but that's fine: you can use Promise.all with a list of MyPromises.
Related
To profile my app more detailed I need to know which promises not awaited but... js not provide such ability.
In python every time when result of async function is not awaited it prints warring
But how to obtain such result in js?
I concluded to do so I have to know few things:
how to override promise construction (to add state field which will show is promise awaited and to set timeout to check state)
what triggered when object awaited (to change state)
I figured out via Proxy that when awaiting, object's then property is called:
async function test(obj) {
await obj
}
test(new Proxy(new Object(), {
get(obj, name) {
console.log("get " + name)
}
})
But actually, as turned out, it happens only with non-promise objects
So when I tried to do this:
Promise.prototype.then = function() {
console.log("called then")
}
test(Promise.resolve({}))
I got nothing in output.
Same things with Promise.prototype.constructor and Promise.resolve:
let getOne = async () => 1
getOne()
getOne neither call Promise constructor nor Promise.resolve.
So what I'm doing wrong ?
How actually async/await creates promises and fetch value from them under the hood, and how can it be overridden ?
I figured out via Proxy that when awaiting, object's then property is called
Indeed, that is correct.
when I tried to do [...] test(Promise.resolve({})) I got nothing in output.
That is because in this code -- contrary to your earlier test with await -- you do not execute an await or a then call here. You just construct a promise, and your proxy object is not trapping the creation of a promise, only the execution of the then method.
This brings us back to your first bullet point:
how to override promise construction?
You cannot.
We have access to the Promise constructor, but there is no way you can trap its execution. If you would make a proxy for it -- with a construct handler -- it would not be called, as the JavaScript engine will still refer to the original Promise constructor when -- for instance -- an async function is executed. So you are without hope here.
I don't believe overriding is something you want. Usually async is telling node that this function is asynchronious and if you have something in the event loop that is "long" procedure such as querying another API or reading IO then those functions will yield promises. You can also try using the following:
return new Promise((resolve, reject) => {... do stuff and call resolve() or reject() based on the expected output})
The returned value will be a promise.
To handle the promise you will need to await it.
To get promise from
let getOne = async () => 1 you will need to make it
let getOne = async () => return new Promise((resolve, reject) => return resolve(1))
To obtain the value later you will need to call await getOne()
I'm trying to return promises from a promise and run Promise.all like this:
updateVideos()
.then(videos => {
return videos.map(video => updateUrl({ id: video, url: "http://..." }))
})
.then(Promise.all) // throw Promise.all called on non-object
How can I use this kind of Promise.all. I know .then(promises => Promise.all(promises)) works. But, just trying to know why that failed.
This happens with Express res.json too. The error message is different, but I think the reason is same.
For example:
promise().then(res.json) // Cannot read property 'app' of undefined
does not work but
promise().then(results =>res.json(results))
does.
all needs to be called with this referring to Promise (or a subclass), so you'd need:
.then(promises => Promise.all(promises))
or
.then(Promise.all.bind(Promise))
It's important because all needs to work correctly when inherited in Promise subclasses. For instance, if I do:
class MyPromise extends Promise {
}
...then the promise created by MyPromise.all should be created by MyPromise, not Promise. So all uses this. Example:
class MyPromise extends Promise {
constructor(...args) {
console.log("MyPromise constructor called");
super(...args);
}
}
console.log("Creating two generic promises");
const p1 = Promise.resolve("a");
const p2 = Promise.resolve("a");
console.log("Using MyPromise.all:");
const allp = MyPromise.all([p1, p2]);
console.log("Using then on the result:");
allp.then(results => {
console.log(results);
});
.as-console-wrapper {
max-height: 100% !important;
}
Details in the spec. (Which I'm going to have to re-read in order to understand why five calls to MyPromise are made when I call MyPromise.all in the above.)
TJ Crowder's response explained why this happens. But if you are looking for a different solution, BluebirdJS (an npm promise library) handles this situation a bit differently. The following code works fine for me.
Using bluebird can also be helpful for dealing with promises that need to be executed and evaluated sequentially. mapSeries has been a life-saver for me.
import * as Promise from "bluebird"
// ...
Promise.resolve()
.then(() => arrayOfPromises)
.then(Promise.all)
I'm trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing them, sending them through template engines, etc.
So my question is, would it be unwise to have my constructor function return a promise instead of an object of the function they called new against.
For instance:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Now, the user may also not supply a supplement Promise chain link:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
This could pose a problem as the user may be confused why engine is not available after construction.
The reason to use a Promise in the constructor makes sense. I want the entire blog to be functioning after the construction phase. However, it seems like a smell almost to not have access to the object immediately after calling new.
I have debated using something along the lines of engine.start().then() or engine.init() which would return the Promise instead. But those also seem smelly.
Edit: This is in a Node.js project.
Yes, it is a bad practise. A constructor should return an instance of its class, nothing else. It would mess up the new operator and inheritance otherwise.
Moreover, a constructor should only create and initialize a new instance. It should set up data structures and all instance-specific properties, but not execute any tasks. It should be a pure function without side effects if possible, with all the benefits that has.
What if I want to execute things from my constructor?
That should go in a method of your class. You want to mutate global state? Then call that procedure explicitly, not as a side effect of generating an object. This call can go right after the instantiation:
var engine = new Engine()
engine.displayPosts();
If that task is asynchronous, you can now easily return a promise for its results from the method, to easily wait until it is finished.
I would however not recommend this pattern when the method (asynchronously) mutates the instance and other methods depend on that, as that would lead to them being required to wait (become async even if they're actually synchronous) and you'd quickly have some internal queue management going on. Do not code instances to exist but be actually unusable.
What if I want to load data into my instance asynchronously?
Ask yourself: Do you actually need the instance without the data? Could you use it somehow?
If the answer to that is No, then you should not create it before you have the data. Make the data ifself a parameter to your constructor, instead of telling the constructor how to fetch the data (or passing a promise for the data).
Then, use a static method to load the data, from which you return a promise. Then chain a call that wraps the data in a new instance on that:
Engine.load({path: '/path/to/posts'}).then(function(posts) {
new Engine(posts).displayPosts();
});
This allows much greater flexibility in the ways to acquire the data, and simplifies the constructor a lot. Similarly, you might write static factory functions that return promises for Engine instances:
Engine.fromPosts = function(options) {
return ajax(options.path).then(Engine.parsePosts).then(function(posts) {
return new Engine(posts, options);
});
};
…
Engine.fromPosts({path: '/path/to/posts'}).then(function(engine) {
engine.registerWith(framework).then(function(framePage) {
engine.showPostsOn(framePage);
});
});
I encountered the same problem and came up with this simple solution.
Instead of returning a Promise from the constructor, put it in this._initialized property, like this:
function Engine(path) {
this._initialized = Promise.resolve()
.then(() => {
return doSomethingAsync(path)
})
.then((result) => {
this.resultOfAsyncOp = result
})
}
Then, wrap every method in a callback that runs after the initialization, like that:
Engine.prototype.showPostsOnPage = function () {
return this._initialized.then(() => {
// actual body of the method
})
}
How it looks from the API consumer perspective:
engine = new Engine({path: '/path/to/posts'})
engine.showPostsOnPage()
This works because you can register multiple callbacks to a promise and they run either after it resolves or, if it's already resolved, at the time of attaching the callback.
This is how mongoskin works, except it doesn't actually use promises.
Edit: Since I wrote that reply I've fallen in love with ES6/7 syntax so there's another example using that.
class Engine {
constructor(path) {
this._initialized = this._initialize(path)
}
async _initialize() {
// actual async constructor logic
this.resultOfAsyncOp = await doSomethingAsync(path)
}
async showPostsOnPage() {
await this._initialized
// actual body of the method
}
}
To avoid the separation of concerns, use a factory to create the object.
class Engine {
constructor(data) {
this.data = data;
}
static makeEngine(pathToData) {
return new Promise((resolve, reject) => {
getData(pathToData).then(data => {
resolve(new Engine(data))
}).catch(reject);
});
}
}
The return value from the constructor replaces the object that the new operator just produced, so returning a promise is not a good idea. Previously, an explicit return value from the constructor was used for the singleton pattern.
The better way in ECMAScript 2017 is to use a static methods: you have one process, which is the numerality of static.
Which method to be run on the new object after the constructor may be known only to the class itself. To encapsulate this inside the class, you can use process.nextTick or Promise.resolve, postponing further execution allowing for listeners to be added and other things in Process.launch, the invoker of the constructor.
Since almost all code executes inside of a Promise, errors will end up in Process.fatal
This basic idea can be modified to fit specific encapsulation needs.
class MyClass {
constructor(o) {
if (o == null) o = false
if (o.run) Promise.resolve()
.then(() => this.method())
.then(o.exit).catch(o.reject)
}
async method() {}
}
class Process {
static launch(construct) {
return new Promise(r => r(
new construct({run: true, exit: Process.exit, reject: Process.fatal})
)).catch(Process.fatal)
}
static exit() {
process.exit()
}
static fatal(e) {
console.error(e.message)
process.exit(1)
}
}
Process.launch(MyClass)
This is in typescript, but should be easily converted to ECMAscript
export class Cache {
private aPromise: Promise<X>;
private bPromise: Promise<Y>;
constructor() {
this.aPromise = new Promise(...);
this.bPromise = new Promise(...);
}
public async saveFile: Promise<DirectoryEntry> {
const aObject = await this.aPromise;
// ...
}
}
The general pattern is to store the promises as internal variables using the constructor and await for the promises in the methods and make the methods all return promises. This allows you to use async/await to avoid long promise chains.
The example I gave is good enough for short promises, but putting in something that requires a long promise chain will make this messy, so to avoid that create a private async method that will be called by the constructor.
export class Cache {
private aPromise: Promise<X>;
private bPromise: Promise<Y>;
constructor() {
this.aPromise = initAsync();
this.bPromise = new Promise(...);
}
public async saveFile: Promise<DirectoryEntry> {
const aObject = await this.aPromise;
// ...
}
private async initAsync() : Promise<X> {
// ...
}
}
Here is a more fleshed out example for Ionic/Angular
import { Injectable } from "#angular/core";
import { DirectoryEntry, File } from "#ionic-native/file/ngx";
#Injectable({
providedIn: "root"
})
export class Cache {
private imageCacheDirectoryPromise: Promise<DirectoryEntry>;
private pdfCacheDirectoryPromise: Promise<DirectoryEntry>;
constructor(
private file: File
) {
this.imageCacheDirectoryPromise = this.initDirectoryEntry("image-cache");
this.pdfCacheDirectoryPromise = this.initDirectoryEntry("pdf-cache");
}
private async initDirectoryEntry(cacheDirectoryName: string): Promise<DirectoryEntry> {
const cacheDirectoryEntry = await this.resolveLocalFileSystemDirectory(this.file.cacheDirectory);
return this.file.getDirectory(cacheDirectoryEntry as DirectoryEntry, cacheDirectoryName, { create: true })
}
private async resolveLocalFileSystemDirectory(path: string): Promise<DirectoryEntry> {
const entry = await this.file.resolveLocalFilesystemUrl(path);
if (!entry.isDirectory) {
throw new Error(`${path} is not a directory`)
} else {
return entry as DirectoryEntry;
}
}
public async imageCacheDirectory() {
return this.imageCacheDirectoryPromise;
}
public async pdfCacheDirectory() {
return this.pdfCacheDirectoryPromise;
}
}
I know that it's not the best approach to overwrite native JS API and I do it more for experiment.
I would like to overwrite Promise resolve method handler to do some extra logic on each resolve. Is it possible?
Yes, it's possible. You have to wrap Promise.prototype.then method.
Promise.prototype.then = (oldThen=>{
return function then(_successHandler, _rejectHandler){
/* your logic here;
remember: both successHandler and rejectHandler can be non-functions */
return oldThen.call(this, wrappedSuccessHandler, wrappedRejectHandler);
}
})(Promise.prototype.then);
This code won't be able to intercept new Promise() calls, but there is other workaround for this:
class SubPromise extends Promise {
constructor(executor) {
super(function(_resolve, _reject) {
/* your code goes here */
return executor(wrappedResolve, wrappedReject);
});
}
then(success, reject) {
return super.then(wrappedSuccessHandler, wrappedRejectHandler);
}
}
window.Promise = SubPromise;
It replaces global Promise property with your implementation, so all subsequent calls resolving to window.Promise will return your implementation.
See 25.4.5.3 Promise.prototype.then in spec for further details (with default handlers "thrower" and "identity").
I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments. For example:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled('arg1', 'arg2');
})
such that my code:
promise.then(function(arg1, arg2){
// ....
});
would receive both arg1 and arg2?
I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.
I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.
Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.
I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.
That's where I believe you're wrong. The specification is designed to be minimal and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with .spread for a while now. For example:
Promise.try(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c); // "Hello World!";
});
With Bluebird. One solution if you want this functionality is to polyfill it.
if (!Promise.prototype.spread) {
Promise.prototype.spread = function (fn) {
return this.then(function (args) {
return Promise.all(args); // wait for all
}).then(function(args){
//this is always undefined in A+ complaint, but just in case
return fn.apply(this, args);
});
};
}
This lets you do:
Promise.resolve(null).then(function(){
return ["Hello","World","!"];
}).spread(function(a,b,c){
console.log(a,b+c);
});
With native promises at ease fiddle. Or use spread which is now (2018) commonplace in browsers:
Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
console.log(a,b+c);
});
Or with await:
let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);
You can use E6 destructuring:
Object destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled({arg1: value1, arg2: value2});
})
promise.then(({arg1, arg2}) => {
// ....
});
Array destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled([value1, value2]);
})
promise.then(([arg1, arg2]) => {
// ....
});
The fulfillment value of a promise parallels the return value of a function and the rejection reason of a promise parallels the thrown exception of a function. Functions cannot return multiple values so promises must not have more than 1 fulfillment value.
As far as I can tell reading the ES6 Promise specification and the standard promise specification theres no clause preventing an implementation from handling this case - however its not implemented in the following libraries:
RSVP.promise (#L516-544)
Q promise (#787)
I assume the reason for them omiting multi arg resolves is to make changing order more succinct (i.e. as you can only return one value in a function it would make the control flow less intuitive) Example:
new Promise(function(resolve, reject) {
return resolve(5, 4);
})
.then(function(x,y) {
console.log(y);
return x; //we can only return 1 value here so the next then will only have 1 argument
})
.then(function(x,y) {
console.log(y);
});
De-structuring Assignment in ES6 would help here.For Ex:
let [arg1, arg2] = new Promise((resolve, reject) => {
resolve([argument1, argument2]);
});
Here is a CoffeeScript solution.
I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS
the answer of this guy Florian
promise = deferred.promise
promise.success = (fn) ->
promise.then (data) ->
fn(data.payload, data.status, {additional: 42})
return promise
promise.error = (fn) ->
promise.then null, (err) ->
fn(err)
return promise
return promise
And to use it:
service.get().success (arg1, arg2, arg3) ->
# => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
# => err
Great question, and great answer by Benjamin, Kris, et al - many thanks!
I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:
npm i -S promise-spread
Then in your code, do
require('promise-spread');
If you're using a library such as any-promise
var Promise = require('any-promise');
require('promise-spread')(Promise);
Maybe others find this useful, too!
Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled() method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled() method as long as the promise's value is the first argument.
2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.
To quote the article below, ""then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only."
I usually look to this page for any basic promise questions, let me know if I am wrong
http://www.html5rocks.com/en/tutorials/es6/promises/