【问题标题】:How to convert nested callbacks to promises如何将嵌套回调转换为 Promise
【发布时间】:2018-09-19 15:54:56
【问题描述】:

我有嵌套的回调导致问题。我想改变承诺,但我不确定该怎么做。

我首先得到一个输出数组

require('abcd').open(cnnectionString, function(er, conn) {  
    // I get list back from following query
   conn.query('select first 10 name, phone from........', function(err, result) {
       if(err) {
       } else {
           // for each name and phone I call another query
           for(i = 0; i <= result.length; i++) {
                conn.query('select address from......where name=result[i].name',  
                function(error, result1) {
                     // I call third query based on data from second query
                     conn.query('select acct from .......where ', function(err, result2) { 
                          console.log(result2)
                     })  
                })                
           })
})

使用这种方法,由于异步,我会得到各种不好的结果。请让我知道如何将其更改为承诺。

【问题讨论】:

  • 第一步。将 Promise 接口用于您的数据库,找到它的使用示例并开始使用它而不是回调接口。您需要阅读一些文档和一些教程才能做到这一点。对于循环中的多个异步操作,了解如何使用Promise.all() 跟踪多个异步操作。
  • 我希望这个视频能对你有所帮助youtube.com/watch?v=2d7s3spWAzo&t=4s
  • 您应该首先将三个嵌套查询变成一个查询:利用数据库的强大功能一次性生成这些结果。

标签: javascript node.js callback promise


【解决方案1】:

您可以使用Promise.all() 实现此目的,请看下面并尝试一下:

var connection;
var promises = [];
require('abcd').open(cnnectionString)
  .then(function(conn) {
    connection = conn;
    return connection.query('select first 10 name, phone from........');    
  })
  .then(function(result) {
    for (i=0; i<=result.length; i++) {
      var promise = connection.query('select address from......where name=result[i].name');      
      promises.push(promise);
    }    
  })
  .catch(function(err) {
    console.log(err, 'error');
  });

Promise.all(promises).then(function(result) {
  console.log(result, 'result');
});

【讨论】:

  • 它给出了第一个查询的结果第二个查询有错误 conn not defined on line where var promises=conn.query.....
  • @J.Davidson 是的,我刚刚看到并更新了我的答案,请看一下,创建一个变量连接并使用connection = conn。虽然如果我们使用 arrow-functions 就不需要它了
  • 是的,我在输入评论后看到了。我有第三个查询,我需要从结果中获取一个值并运行它,如果它在打印结果的地方也需要推送承诺,或者只是可以不用它。谢谢你的帮助
  • 是的,查询运行后的所有逻辑都可以在 all 的 .then 方法的结果中完成。我想您需要跟踪所有返回的承诺。这就是为什么需要数组。
  • @J.Davidson 很高兴为您提供帮助 :)
【解决方案2】:

以下代码可以帮助您了解如何将回调更改为代码中的承诺

var name = require('abcd');
name.open(connectionString)
.then(function(conn) {
    //query
   })
.then(function(other) {
   })
});

你可以通过这些链接了解nodejs中的promise,也有例子 https://developer.ibm.com/node/2016/08/24/promises-in-node-js-an-alternative-to-callbacks/ https://www.guru99.com/node-js-promise-generator-event.html

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2015-06-06
    • 2015-12-11
    • 2020-07-05
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多