我为什么得到承诺{< pending>在Promise.all中使用提取时? [英] Why am I getting Promise { <pending> } when using fetch in Promise.all?

查看:282
本文介绍了我为什么得到承诺{< pending>在Promise.all中使用提取时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很好:

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

我得到Promise { <pending> }作为输出,似乎Promise.all在call()完成之前就运行了

I get Promise { <pending> } as the output, it seems as though the Promise.all get run before call() is completed

推荐答案

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

You have to use .then() on res[1].json() because it just returns a promise and you aren't waiting on that promise anywhere.

我建议您更改为:

let call = fetch(link, { headers: {"Content-Type": "application/json; charset=utf-8"} })
    .then(response => response.json());

然后,您的call变量已经进行了.json()调用,并且Promise.all()将为您等待.

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

这篇关于我为什么得到承诺{&lt; pending&gt;在Promise.all中使用提取时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆