Understanding JS Promises

后端 未结 7 1113
梦如初夏
梦如初夏 2020-11-29 05:50

I would like to get a deeper understanding of how Promises work internally. Therefore I have some sample code:

var p1          


        
7条回答
  •  清歌不尽
    2020-11-29 06:51

    I do not know how this is done in actual promises libraries, but I was able to re-create this functionality in the following way: 1) each promise has a waitingPromises property; 2) then method returns a new promise, and the original promise's waitingPromises property points to the new promise.

    In this way, the chain of .then()s creates a structure that is similar to a linked list or rather a tree (each promise can have several waiting promises). A promise can be resolved only after its 'parent' promise has been resolved. The .then method itself is executed immediately, but the corresponding promise that it creates is resolved only later. I am not sure this is a good explanation and would love to learn about other possible approaches.

提交回复
热议问题