Can the function registered by then get its own re

2019-07-25 16:40发布

问题:

Would the function that is registered/executed by the then method be able to catch hold of its own resolve?

A promise when its constructed is able to inject its resolve method like:

new Promise(function(resolve, reject){ async(resolve();})

However the action registered by then normally is triggered in resolve method like (at least in some examples I have seen):

resolve = function(value){
  self.value = value;
  self.state = "resolved";
  deferred.resolve(deferred.transform(self.value));
}

There is no real means to inject deferred.resolve into deferred.transform method. It almost as if the then doesn't expect the function it would execute to be asynchronous unlike like a Promise Constructor and hence it isn't isomorphic?

In Javascript Promise Sequence you actually create 8 Promises for a job that should ideally be done in 4 Promises. Can't this be solved if the transformation function registered by then can get hold of its own resolve which is the deferred.resolve? The transformation function can be ansychronous and it can resolve it when it's done.

回答1:

Would the function that is registered/executed by the then method be able to catch hold of its own resolve?

No.

Or at least not without returning a thenable that intercepts its callback, but that doesn't really make sense.

It almost as if the then doesn't expect the function it would execute to be asynchronous

Oh, it does. Your misunderstanding seems to be based on thinking that asynchronous functions are those that take callbacks. They aren't. Asynchronous functions are those that return promises! And then is totally capable dealing with them.

…unlike the Promise Constructor

It's the other way round. The Promise constructor is the odd one out here. Its only purpose is to transform old-style callback-taking functions to promises. You're expected to deal with fully promisified functions only these days, and new APIs will return promises right away.