kriskowal/q

Why return function ref ?

indown opened this issue · 6 comments

Now, we need to start altering our "then" methods so that they return promises for the return value of their given callback. The "ref" case is simple. We'll coerce the return value of the callback to a promise and return that immediately.

var ref = function (value) {
    if (value && typeof value.then === "function")
        return value;
    return {
        then: function (callback) {
            return ref(callback(value));
        }
    };
};

I try only to use "return callback(value)", It doesn't seem to be a problem,Can you provide an example (" return callback(value) ")?
Thanks.

Could you elaborate? It's not clear to me what you are trying to achieve and how Q is involved in it

Could you elaborate? It's not clear to me what you are trying to achieve and how Q is involved in it

design/README.md

That's my problem with this document design/README.md.

If you don't call ref on the callback value, the callback might not return a promise and then you wouldn't be able to call p.then(...).then(...)

If you don't call ref on the callback value, the callback might not return a promise and then you wouldn't be able to call p.then(...).then(...)

I try only to use "callback(value)". it would be able to call p.then(...).then(...)
https://jsbin.com/cozuluxido/3/edit?html,js,console,output
Can you provide an example where it doesn't work?

p.then(() => 1) would return 1, would it not?

Of course, there is a school of thought that promises should be strict monads, in which case, the author of the callback would be obliged to wrap/lift the return value in order to satisfy the type of then (which would decompose into map and flatMap).

So p.then(() => ref(1)) would return a promise.

p.then(() => 1) would return 1, would it not?

Of course, there is a school of thought that promises should be strict monads, in which case, the author of the callback would be obliged to wrap/lift the return value in order to satisfy the type of then (which would decompose into map and flatMap).

So p.then(() => ref(1)) would return a promise.

promise: {
            then: function (_callback) {
                let result = defer();
                let callback = function (value) {
                    result.resolve(_callback(value));
                };
                if (pending) {
                    pending.push(callback);
                } else {
                    value.then(callback);
                }
                return result.promise;
            }
        }

So p.then(() => 1) would return a promise.
There is an example on https://jsbin.com/cozuluxido/3/edit?html,js,console,output