4

I'm trying to put a fetch inside a promise, so that I can use it in a Promise.all

let dbconnect = new Promise((rs, rj)=> {
  console.log('dbconnect');
  require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } )
}),

call =  new Promise((rs, rj) =>{ 
  console.log('fetch');
  fetch(link)})
});



Promise.all( [dbconnect, call] ).then...

Both calls get responses, but it doesn't trigger the Promise.all().then, what am I doing wrong?

Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

3

You need to return some result in your promises, otherwise, they won't be passed into the chained .then(). In your case, if you want to use Promise constructors, you should explicitly call resolve() with whatever results you want to pass further, like this:

let dbconnect = new Promise((rs, rj)=> {
  console.log('dbconnect');
  require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true }, () => {
    resolve()
  })
}),

call =  new Promise((rs, rj) =>{ 
  console.log('fetch');
  fetch(link).then(resolve)})
});

But, as other users already mentioned, you probably don't need to wrap fetch() and MongoClient.connect() (since v2.0) into Promises as they already return promises. So you can simplify it into:

let dbconnect = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", {useNewUrlParser: true}),
call = fetch(link)

Promise.all( [dbconnect, call] ).then...
shkaper
  • 4,689
  • 1
  • 22
  • 35
  • Connect *also* returns a promise. – jonrsharpe Nov 10 '18 at 18:31
  • @jonrsharpe Are you sure? https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html#connect says it returns null and you need to pass a callback – shkaper Nov 10 '18 at 18:32
  • 1
    Since 2015, yes: https://github.com/mongodb/node-mongodb-native/blob/2.2/HISTORY.md#2036-2015-07-07 – jonrsharpe Nov 10 '18 at 18:35
  • Thanks, this was my initial soluton, but it had strange results for me, i'm new to promises pretty much, here is my actual problem: https://stackoverflow.com/questions/53242204/why-am-i-getting-promise-pending-when-using-fetch-in-promise-all – Himmators Nov 10 '18 at 18:39