我正在学习 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:1
和 2
(在除了 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/