我正在学习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 …Run Code Online (Sandbox Code Playgroud)