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.