微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript-Promise Chaining如何在内存中工作?

function foo() {
  console.log('foo called')
  return Promise.resolve(5)
}
foo()
  .then(res => {
    console.log(res)
  })
console.log('hi')

控制台输出

1.) 'foo called'

2.) 'hi'

3.) 5

我的主要问题是,当全局执行上下文线程完成并从执行堆栈中弹出时,实际上发生了什么.如果未将Promise对象分配给全局执行上下文中的变量,JS / V8如何知道此Promise对象在内存中的位置?它如何知道在哪里更新Promise值并触发onfullfilment函数

最佳答案
查看the V8 source code,我们可以看到when a Promise is created已绑定到当前执行上下文,即使您没有将其存储在变量中.

Node* const native_context = LoadNativeContext(context);
Node* const promise = AllocateAndInitJSPromise(context);

查看how promises are implemented,我们可以看到Promise解决方案链是作为一个简单的链表(强调我的链)实现的:

The PromiseReaction objects form a singly-linked list […]. On the JSPromise instance they are linked in reverse order,and are turned into the proper order again when scheduling them on the microtask queue.

简而言之,即使您不将Promises存储在变量中,V8也会将Promises绑定到执行上下文,并且Promise链被实现为链接列表,这意味着在Promise实际解决后,很容易进行追溯.

为了更全面地了解异步操作如何进行交互,请查看Javascript事件循环上的this video by Jake Archibald.

原文地址:https://www.jb51.cc/js/531226.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐