簡體   English   中英

我為什么得到承諾{ <pending> 在Promise.all中使用提取時?

[英]Why am I getting Promise { <pending> } when using fetch in 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}));
  })

但是當我嘗試將獲取與另一個承諾結合在一起時:

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()上使用.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]);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM