x_x*_*x_x 7 javascript node.js promise es6-promise
我正在学习Node.js,并尝试正确使用mysql2模块。因此,我最近开始研究诺言。
我正在写一种“库”,因此我可以练习所有这些主题,而在这样做的时候,我遇到了我无法真正理解的承诺链问题。任何帮助都非常感谢!
问题如下:
假设我有一个query函数,该函数可获取数据库,处理数据并返回promise,因此我可以获取该数据并在其他文件中使用它。
现在,如果我这样写我的query函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试像这样从其他文件中“消费”该承诺:
DBObject.query().then((data) => {
console.log("Hello world from the other file!");
})
Run Code Online (Sandbox Code Playgroud)
然后输出顺序错误,程序将输出以下内容:
Hello world a second time!
Hello world from the other file!
Hello world a third time
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我更改第一个文件中的代码,并且不尝试分开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;
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,并且可以打印:
Hello world a second time!
Hello world a third time
Hello world from the other file!
Run Code Online (Sandbox Code Playgroud)
我不了解这种行为,我当时想then与诺言定义分开声明块与声明诺言时对诺言链接的权利是一回事,显然不是这样!
预先感谢您可以给我的答案。另外,如果您能给我一些有关如何正确编写这样的代码的建议,那将是很棒的。我的意思是,如果我编写使用Promise的代码,应该返回给用户什么?另一个承诺?还是只是供他们使用的数据?我真的很想编写遵循“标准”做事方式的代码。
向大家致意!再次感谢你。
当您有一个Promise时,可以将任意数量的Promises链接到其上.then。例如
const p = Promise.resolve();
p.then(() => console.log('then 1');
p.then(() => console.log('then 2');
Run Code Online (Sandbox Code Playgroud)
表示在解决时p有两个从其分支的Promises:1和2(除了Promise p本身)。
p
/ \
/ \
1 2
Run Code Online (Sandbox Code Playgroud)
您在第一个代码中正在做什么
let p = new Promise((resolve, reject) => {
resolve("Hello world")
});
p.then(data => {
console.log("second");
}).then(data => {
console.log("third")
})
return p;
Run Code Online (Sandbox Code Playgroud)
就好像
"Hello world" = <Promise you return>
|
|
|
second
|
|
|
third = <unused Promise expression that the then chain resolves to>
Run Code Online (Sandbox Code Playgroud)
您有两个分支:返回的Promise在Hello world运行时解析,而不是在third运行时解析。
另一方面,当您.then多次在Promise上调用时,整个表达式将计算为Promise,该Promise 在最终.then运行时解析:
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;
Run Code Online (Sandbox Code Playgroud)
就好像
"Hello world"
|
|
'Hello second'
|
|
'Hello third' = <Promise you return>
Run Code Online (Sandbox Code Playgroud)
返回的Promise是Hello third运行后立即解决的Promise 。