1

I'm requesting data from an api and then storing it to a database:

The database

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

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

I could just nest the fetch-response inside the MongoClient, but I would much rather start both requests and then, once they are both done, start a chain of promises. Is this possible?

1 Answer 1

1

If you want to start promises at the same time, you should try to use Promise.All.

Here is an example

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"] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.