This works fine:
....
.then(() => fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} }))
.then( res => res.json())
.then((response)=>{
console.log(util.inspect(response, {showHidden: true, depth: null, colors: true}));
})
But whenI try to combine the fetch with another promise:
let dbconnect = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),
call = fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} });
Promise.all( [dbconnect, call] )
.then( res => [res[0], res[1].json()])
.then( res => {
database = res[0];
sales = res[1];
console.log(util.inspect(res[1], {showHidden: true, depth: null, colors: true}));
})
I get Promise { <pending> }
as the output, it seems as though the Promise.all get run before call()
is completed
You have to use .then()
on res[1].json()
because it just returns a promise and you aren't waiting on that promise anywhere.
What I would suggest is that you change to this:
let call = fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} })
.then(response => response.json());
Then, your call
variable has already made the .json()
call and Promise.all()
will wait on it for you.
let dbconnect = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),
call = fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} })
.then(response => response.json());
Promise.all( [dbconnect, call] ).then( res => {
console.log(res[0]);
console.log(res[1]);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.