Reputation:
My understanding of a Promise object is as follows:
var Promise = {
then: function() { ... },
catch: function() { ... }
};
If I have this code below that has a function and returns a Promise object (fetch.js
):
var xhr = require('xhr')
module.exports = function (uri) {
return new Promise(function (resolve, reject) {
xhr(uri, function (err, res, body) {
if (err) return reject(err)
if (res.statusCode !== 200) return reject(new Error(body))
resolve(body)
})
})
}
Then in my index.js
I do:
var fetch = require('./fetch');
var promise = fetch("some_url");
How is the structure of the promise object returned from var promise = fetch("some_url");
formed?
In the fetch.js
in the new Promise(...)
part you are passing in a function to a constructor. I haven't seen anything like this before and am wondering how the resolve
and reject
parameters in the new Promise(...)
part get passed to the then
and catch
keys in the sample Promise object above.
Upvotes: 1
Views: 174
Reputation: 941
i cant explain but show you example how then function get the resolved value or catch get error
take a variable a save promise to that variable and then execute then function like bellow example
var a = new Promise(function (resolve, reject) {
resolve(1);
})
a.then();
when you execute a.then() it get two parameters PromiseStatus and PromiseValue in promiseStatus you will get it is resolved or reject and in PromiseValue you will get the value you passed with resolve or reject handler
Promise
__proto__
:
Promise
catch:catch()
constructor: Promise()
then:then()
Symbol(Symbol.toStringTag):"Promise"
__proto__:Object[[PromiseStatus]]:"resolved"[[PromiseValue]]:1
Upvotes: 4