最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Javascript - How to use promises with multiple .then() - Stack Overflow

programmeradmin1浏览0评论

I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)

And my code is this:

var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });



    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then() I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

I'm trying to create a array structure. So, we have parts and each part had articles.

So i did a promise to collect all parts .then() i need to iterate part promise and select the articles in this part .then() i want to push this to a array parts and render this in a view.

The structure is this:

-PARTS
      - part
            - u_order
            - u_familia
            - u_part
            - u_type
            - articles (article from each part)

And my code is this:

var p1 = new Promise(function(resolve, reject) {
      var stamp = req.params.stamp;
      request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'").then((data)=>resolve(data));
      // or
      // reject ("Error!");
    });



    p1.then(function(value){
      var stamp = req.params.stamp;
      console.log(value.length);
      for(var i= 0; i<value.length; i++)
      {
        console.log(value[i]);
        request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+value[i].u_order+"'").then((data)=>resolve(data));
      }

    }, function(reason){
      console.log(reason);
    });

    p1.then(function(part, articles){
      var parts = [];
      console.log("PART: " +part.length);
      for(var j= 0; j<part.length; j++)
      {
        console.log(part[j].u_order);
        console.log(part[j].u_familia);
        console.log(part[j].u_part);
        console.log(part[j].u_type);
        console.log(articles[j]);
      };
    });

In last .then() i just have the parts, i can't access to articles maybe because i'm not doing well with second .then() I'm starting working with promises, i also read documentation but i can't do this.

Anyone can help me to understand and solve this?

Share Improve this question edited Mar 9, 2024 at 9:58 Ouroborus 16.9k8 gold badges40 silver badges65 bronze badges asked Mar 30, 2017 at 10:11 user3242861user3242861 1,92912 gold badges53 silver badges97 bronze badges 14
  • a) p1 is the same promise ... so same result ...b) .then callback function accepts a single argument ... which is why articles is undefined – Jaromanda X Commented Mar 30, 2017 at 10:12
  • Ok, so, how can i use both? @JaromandaX – user3242861 Commented Mar 30, 2017 at 10:14
  • Can you give me an example? I understand why this doesn't work but i don't know how to do that. @JaromandaX – user3242861 Commented Mar 30, 2017 at 10:16
  • how can i use both both what? I can't tell what you even think your code should do, so how can I answer that – Jaromanda X Commented Mar 30, 2017 at 10:49
  • Both selects. In first request.query i have an array with all parts and in second i have an array with articles for each part from first request.query. After that i have to access both arrays to do parts.push. Do you understand? @JaromandaX – user3242861 Commented Mar 30, 2017 at 10:54
 |  Show 9 more comments

2 Answers 2

Reset to default 7

The best I can do.

request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(function(parts){
    var stamp = req.params.stamp;
    return Promise.all(parts.map(function(part) {
        return request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+part.u_order+"'")
        .then(function(articles) {
            part.articles = articles;
            return part;
        });
    }));
})
.then(function(parts){
    parts.forEach(function(part) {
        console.log(part.u_order);
        console.log(part.u_familia);
        console.log(part.u_part);
        console.log(part.u_type);
        part.articles.forEach(function(article) {
            console.log(article.u_posic);
            console.log(article.ref);
            console.log(article.qtt);
            console.log(article.design);
        });
    });
});

BONUS ES2015+ version of above

request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'")
.then(parts => Promise.all(parts.map(part => request.query(`SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='${req.params.stamp}' and st.u_posic = '${part.u_order}'`)
    .then(articles => {
        part.articles = articles;
        return part;
    })
)))
.then(parts => parts.forEach(part => {
    console.log(part.u_order);
    console.log(part.u_familia);
    console.log(part.u_part);
    console.log(part.u_type);
    part.articles.forEach(article => {
        console.log(article.u_posic);
        console.log(article.ref);
        console.log(article.qtt);
        console.log(article.design);
    });
}));

You got it wrong.

  • First promise.prototype.then resolve with just one Argument. Please check docs

  • And second thing promise return a promise, so you are just calling a query resolving there only, so no change in first resolved data and while chaining it will just pass the first data as it is

  • You can do this with two ways
    • First One : By taking a global variable :
const $Vals = {};
function A() {
  return new Promise((resolve, reject) => {
    resolve([1, 2, 3])
  })
}

function B() {
  return new Promise((resolve, reject) => {
    resolve([4, 5, 6])
  })
}



A().then((dt) => {
  $Vals.A = dt;
  return B();
}).then((dt) => {
  $Vals.B = dt;
  console.log('%j', $Vals);
})

output: {"A":[1,2,3],"B":[4,5,6]}

  • Second which is more suitable by passing a custom promise :
A().then((dt) => new Promise((resolve) => {
  B().then((bData) => {
    resolve({
      A:dt,
      B:bData,
    })
  })
})).then((combined) => {
  console.log('%j', combined);
})

Output: {"A":[1,2,3],"B":[4,5,6]}
发布评论

评论列表(0)

  1. 暂无评论