javascript - 为什么在 Promise.all 中使用 fetch 时会收到 Promise { <pending> }?

标签 javascript node.js ecmascript-6

这工作正常:

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

相关文章:

javascript - fs.readdirSync,如何获取路径中的子文件夹?

node.js - 尝试查询 dynamodb 时,Lambda 函数返回 401 错误

javascript - Nodejs 过滤数据并将其作为响应发送

Javascript - 如何从嵌套对象中删除项目?

javascript - 如何只触发一个复选框检查操作

c# - 两个字符串特殊连接的更好方法

javascript - 为什么 Angular-Datatables 插件按钮不起作用

javascript - ES6/React "this"关键字与 ajax 从服务器获取数据(教程)

javascript - 使用javascript从现有对象创建一个对象

javascript - 检查是否 innerHTML 里面包含任何 HTML 标签