繁体   English   中英

节点获取的承诺

[英]Promises with node-fetch

我知道这是一个很常见的问题,但我找不到对此的解释,我正在尝试使用文档示例和 go

const fetch = require("node-fetch");

fetch(final_url, params)
  .then((res) => {
    console.log(res.ok);
    console.log(res.status);
    console.log(res.statusText);
    console.log(res.headers.raw());
    console.log(res.headers.get("content-type"));
  })
  .then((res) => res.json())
  .then((json) => console.log(json))
  .catch((err) => console.log(err));

我有 output 我的final_urlparams变量,它们是正确的,但除了Promise { pending }之外,我什么都没有得到。 据我了解,第二个then解析 Promise 并将其传递给最终then ,它应该是 output 。

我所做的是放置一些断点并使用 vscode 逐步执行每个断点。 我仍然能够看到 Promise { pending },但我不确定我如何才能 go 找出问题所在。 也许有一种方法可以更有效地使用调试器? 任何帮助深表感谢!

似乎returnfirst then中丢失了。 您需要返回以使其在 2 日可用。

每次当你然后,它会创建一个 promise 供下一个像链一样解析。 因此,如果您在 then 中返回“something”,它将类似于返回Promise.resolve("something")

fetch(final_url, params)
  .then((res) => {
    console.log(res.ok);
    console.log(res.headers.get("content-type"));
    return res /// return is missing for next then
  })

样本:

 const promise = new Promise((r) => { setTimeout(r, 1000, 100); }); promise.then((num) => { console.log("1", num); return num * 2; }).then((num) => { console.log("2", num); return num; }); // Output: 1 100 2 200

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM