How to put a fetch inside a Promise?

Viewed 2103

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?

1 Answers

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...
Related