如何链接承诺和多个异步请求?

时间:2018-11-10 17:12:33

标签: node.js

我要从api请求数据,然后将其存储到数据库:

数据库

MongoClient.connect(url, { useNewUrlParser: true })
  .then((db)=>{
    let dbo = db.db("scraper");
    // This will be the api-response:
    dbo.collection("sold").insertOne(
       { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
    )
    db.close();
  })
  .catch(err => {
      console.log(err)
  });

api

fetch(link, {headers: {"Content-Type": "application/json; charset=utf-8"}})
    .then(res =>  res.json()) // parse response as JSON (can be res.text() for plain response)
    .then(response => {
        console.log(util.inspect(response, {showHidden: false, depth: null, colors: true}));
        // This is where I'll be storing the data
    })
    .catch(err => {
        console.log(err)
    });

我可以将获取响应嵌套在MongoClient中,但我宁愿启动这两个请求,然后在完成这两个请求后启动承诺链。这可能吗?

1 个答案:

答案 0 :(得分:1)

如果您想同时开始承诺,则应尝试使用Promise.All。

这是一个例子

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]