简体   繁体   English

Javascript:promise链接后返回promise

[英]Javascript: return promise after promise chaining

JavaScript newbie question here: I want to be able to write a function that participates in a promise chain, while doing some promise chaining within it. JavaScript 新手问题:我希望能够编写一个参与 promise 链的 function,同时在其中进行一些 promise 链接。 After the last promise within the chain results, I want to return that promise so that a chain outside the function can continue.在链结果中的最后一个 promise 之后,我想返回 promise 以便 function 之外的链可以继续。 Here's my example code.这是我的示例代码。 The interesting part is pseudocoded in line 10,有趣的部分是第 10 行的伪代码,

 .then(now return this promise);

what is the correct syntax or methodology for doing this?这样做的正确语法或方法是什么?

function setUpConnection() {
  // do whatever
  return client;
}

function doSomeQueries(client) {
  client.query("doSomeSqlHere")
    .then(client.query, "doSomeMoreSqlHere")
    .then(client.query, "do a third query")
    .then(now return this promise);
}

client = setupConnection();
client.connect()
  .then(doSomeQueries(client))
  .then(client.close());

I remember how I wanted to chain everything when I just started using promises, and how I was shocked by the simplicity of the understanding that it's not required.我记得当我刚开始使用 promises 时我是多么想把所有东西都链接起来,以及我是如何对不需要它的理解的简单性感到震惊。 You can stop chaining and save reference to any point of the chain您可以停止链接并保存对链的任何点的引用

function doSomeQueries(client) {
  let promise = client.query("doSomeSqlHere")
    .then(client.query, "doSomeMoreSqlHere")
    .then(client.query, "do a third query")
  return promise; // you can return either Promise<Value> or Value here
}

client = setupConnection();
client.connect()
  .then(doSomeQueries(client))
  .then(client.close());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM