Promise和Promise链如何工作? [代码问题] [英] How promises and promise chaining works? [Problem with code]

查看:69
本文介绍了Promise和Promise链如何工作? [代码问题]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning Node.js and trying to properly use the mysql2 module. Because of this, I have recently started researching about promises.

我正在写一种图书馆,因此我可以练习所有这些主题,同时做到这一点。 ,我遇到了我不太了解的承诺链问题。

I'm writing a kind of "library", so I can practice all these topics, and while doing that, I got into a problem with promise chaining I can't really understand. Any help is well appreciated!

问题如下:

假设我有一个 query 函数,用于获取数据库,处理数据并返回Promise,因此我可以获取该数据并在其他文件中使用它。

Let's say that I have a query function which fetches the database, process the data and returns a promise, so I can get that data and work with it in some other file.

现在,如果我编写这样的 query 函数:

Now, if I write my query function like this:


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;
    }

然后我尝试从其他文件消费该承诺像这样:

and I try to "consume" that promise from other file like this:


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

然后输出顺序错误,程序将输出以下内容:

Then the output is in the wrong order, the program prints this:

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






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


On the other hand, if I change the code in the first file, and I don't try to separate promise chaining, like this:

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;
    }

它工作得很好,并且可以打印:

It works just fine, and it prints:

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

我不了解这种行为,我当时想声明然后与promise定义分开的块与当我声明promise时promise链接正确一样,而且显然不是这样!

I don't understand this behaviour, I was thinking that declaring then blocks separately from the promise definition would be the same thing as do promise chaining right when I declare the promise, and it is clearly not like that!

预先感谢您可以给我的答案。另外,如果您能给我一些有关如何正确编写这样的代码的建议,那将是很棒的。我的意思是,如果我编写使用Promise的代码,应该返回给用户什么?另一个承诺?还是只是供他们使用的数据?我真的很想编写遵循标准方式的代码。

Thanks beforehand for the answers you can give me. Also, It would be great if you could give me some suggestion on how to write code like this correctly. I mean, if I write code that uses promises, what should I return to the user? Another promise? Or just data for they to work with? I would really like writing code that follow the "standard" way of doing things.

向大家致意!再次感谢您。

Greets to you all! Thank you again.

推荐答案

拥有一个Promise时,您可以将任意数量的链式链接到其。然后。例如,

When you have one Promise, you can chain any number of Promises onto its .then. For example

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

表示 p 具有两个解析时从该分支承诺: 1 2 (除了承诺 p 本身)。

means that p has two Promises that branch from it when it resolves: 1 and 2 (in addition to the promise p itself).

  p
 / \
/   \
1   2

您在第一个代码中所做的事情

What you're doing in your first code

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>

您有两个兄弟痛苦:您返回的承诺会在 Hello world 运行时解决,而不是在 third 运行时解决。

You have two branches: the Promise you're returning resolves when Hello world runs, not when third runs.

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

On the other hand, when you call .then multiple times on a Promise, the whole expression evaluates to the Promise that resolves when the final .then runs:

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三分之一之后解析的Promise。 code>运行。

where the returned Promise is the one that resolves right after Hello third runs.

这篇关于Promise和Promise链如何工作? [代码问题]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆