javascript - 承诺:节点 js 中的异步流
问题描述
嗨,我是异步编程的新手。我无法理解如果承诺成功解决,代码是否仍然是异步的。例如:模块 A 具有返回承诺的函数 A()。我需要模块 B 中的模块 A 并调用函数 A() 模块 B 中的代码如下所示:
Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {
somevariableInModuleB = result;
// assign the result from A() to some variable in module B.
// some more logic goes here....
});
Section Z: some more code in module B....
那么,这段代码是否同步执行,即先是 X 部分,然后是 Y 部分,然后是 Z 部分?还是我必须像这样修改它:
Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {somevariableInModuleB = result;})
Section Z: .then(() => {some more code in module B....});
这能保证吗?
解决方案
只有里面的代码then()
会被同步执行。
在您的顶级示例中,Z 部分可能会在 B 部分中的承诺内的代码之前执行。
在您的底部示例中, thethen()
未附加到承诺,因此不起作用。
要使其同步,您希望将其更改为如下所示:
Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {
somevariableInModuleB = result;
some more code in module B....
})
你想做的任何事情result
都必须发生在里面.then()
。
推荐阅读
- mysql - 如何在mysql中的两个日期范围内获取每天的每小时数据?
- java - Java ArrayIndexOutOfBoundsException:999
- visual-studio-code - 将 Bootstrap 链接到我的 VS Code 项目
- android-studio - 结构 R.id.name 中的所有字母 R 变为红色
- metrics - Micronaut:如何获取 Prometheus 格式的指标?
- php - php if elseif 循环不能正常工作
- asp.net-mvc - asp.net core web API文件上传和“form-data”多个参数传递给方法
- python - 通过代理 pip 安装包
- google-cloud-platform - Write into different project's datastore and GBQ using GAE
- firebase - 如何从 Firebase 身份验证中获取用户 ID?