这工作正常:
....
.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}));
})
但是当我尝试将获取与另一个 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}));
})
我得到Promise { <pending> }
作为输出,看起来 Promise.all 在 call()
之前运行已完成
最佳答案
您必须在 res[1].json()
上使用 .then()
,因为它只是返回一个 promise ,而您不会在任何地方等待该 promise 。
我建议你更改为:
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]);
});
关于javascript - 为什么在 Promise.all 中使用 fetch 时会收到 Promise { <pending> }?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242204/