这很好:
....
.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}));
})
但是当我尝试将获取与另一个承诺结合在一起时:
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}));
})
我得到Promise { <pending> }
作为输出,似乎Promise.all在call()
完成之前就运行了
答案 0 :(得分:0)
您必须在.then()
上使用res[1].json()
,因为它只会返回一个承诺,并且您不会在任何地方等待该承诺。
我建议您更改为:
let call = fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} })
.then(response => response.json());
然后,您的call
变量已经进行了.json()
调用,Promise.all()
将为您等待。
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]);
});