javascript - promise 和 promise 链是如何工作的? [代码问题]

标签 javascript node.js promise es6-promise

我正在学习 Node.js 并尝试正确使用 mysql2 模块。因此,我最近开始研究 promises。

我正在编写一种“库”,因此我可以练习所有这些主题,而在这样做的同时,我遇到了一个我无法真正理解的 promise 链问题。非常感谢任何帮助!

问题如下:

假设我有一个 query 函数,它可以获取数据库、处理数据并返回一个 promise ,这样我就可以获取该数据并在其他文件中使用它。

现在,如果我像这样编写我的查询函数:


query(){
        let p = new Promise((resolve, reject) => {
            resolve("Hello world")
        });


        p.then(data => {
            console.log("Hello world a second time!");
        }).then(data => {
            console.log("Hello world a third time")
        })
        return p;
    }

然后我尝试像这样“消费”来自其他文件的 promise :


DBObject.query().then((data) => {
    console.log("Hello world from the other file!");
})

那么输出的顺序就错了,程序打印出这样的:

Hello world a second time!
Hello world from the other file!
Hello world a third time


另一方面,如果我更改第一个文件中的代码,并且我不尝试分离 promise 链,如下所示:

query(){
        let p = new Promise((resolve, reject) => {
            resolve("Hello world")
        }).then(data => {
            console.log("Hello world a second time!");
        }).then(data => {
            console.log("Hello world a third time")
        })

        return p;
    }

它工作得很好,它打印:

Hello world a second time!
Hello world a third time
Hello world from the other file!

我不明白这种行为,我在想从 promise 定义中单独声明 then block 与在我声明 promise 时正确地进行 promise 链接是一样的,而且很明显不是那样的!

预先感谢您给我的答案。另外,如果你能给我一些关于如何正确编写这样的代码的建议,那就太好了。我的意思是,如果我编写使用 promise 的代码,我应该返回给用户什么?另一个 promise ?或者只是供他们使用的数据?我真的很想编写遵循“标准”做事方式的代码。

大家好!再次感谢。

最佳答案

当你有一个 Promise 时,你可以将 任意数量 Promise 链接到它的 .then 上。例如

const p = Promise.resolve();
p.then(() => console.log('then 1');
p.then(() => console.log('then 2');

意味着 p两个 在它解析时从它分支的 Promise:12(在除了 promise p 本身)。

  p
 / \
/   \
1   2

你在你的第一个代码中做了什么

let p = new Promise((resolve, reject) => {
  resolve("Hello world")
});
p.then(data => {
  console.log("second");
}).then(data => {
  console.log("third")
})
return p;

就像

"Hello world" = <Promise you return>
    |
    |
    |
  second
    |
    |
    |
  third = <unused Promise expression that the then chain resolves to>

您有两个分支:您返回的 Promise 在 Hello world 运行时解析,而不是在 third 运行时解析。

另一方面,当您在 Promise 上多次调用 .then 时,整个表达式的计算结果为解析 当最终 .then 时的 Promise运行:

let p = new Promise((resolve, reject) => {
  resolve("Hello world")
}).then(data => {
  console.log("Hello world a second time!");
}).then(data => {
  console.log("Hello world a third time")
})

return p;

就像

"Hello world"
     |
     |
'Hello second'
     |
     |
'Hello third' = <Promise you return>

其中返回的 Promise 是在 Hello third 运行后立即解析的 Promise。

关于javascript - promise 和 promise 链是如何工作的? [代码问题],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565326/

相关文章:

javascript - 如何使用innerHTML将从本地存储检索到的对象传递到DOM中?

node.js - Swift 错误读取 Cloud Code 错误

node.js - 从开发环境将 React 应用程序部署到 Heroku 后,Fetch 请求中断 - 所有 GET 请求返回 index.html - 其他为 404

javascript - 将 Node 异步代码转换为 Promise

javascript - Mysql OR 语句使用 AJAX 返回数组中的所有行名称值,然后在 Google Maps API V3 中加载多个标记

javascript - React 子组件未使用来自 redux 的 prop 重新渲染

javascript - 将值从 'this' 传递到 Promise 的 'then' 函数的正确方法

javascript - JS — FLIP 技术和 requestAnimationFrame,重构为不嵌套

javascript - 如何从 click() 函数内的动画队列返回 true/false?

node.js - Nodejs 部署到 Heroku 时出错