【问题标题】:Why am I getting Promise { <pending> } when using fetch in Promise.all?为什么在 Promise.all 中使用 fetch 时会收到 Promise { <pending> }?
【发布时间】:2018-11-11 03:00:25
【问题描述】:

这很好用:

....
.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}));
  })

但是当我尝试将 fetch 与另一个 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 { &lt;pending&gt; } 作为输出,似乎Promise.all 在call() 完成之前运行

【问题讨论】:

  • 您实际上并没有解决 JSON 的承诺,您只是返回一个包含它的数组。为什么不包括在 call 中解包 JSON?
  • @jonrsharpe 我明白了,但不知道该怎么做,因为我也想包含 res[0] ...
  • 首先让它成为您传递给所有人的链条的一部分吗?或者让res[1].json() 上的回调也通过res[0]
  • 天才就在那里!!

标签: javascript node.js ecmascript-6


【解决方案1】:

您必须在res[1].json() 上使用.then(),因为它只是返回一个承诺,而您不会在任何地方等待该承诺。

我建议你改成这样:

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]);
});

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多