首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用node-fetch的承诺

使用node-fetch的承诺
EN

Stack Overflow用户
提问于 2020-05-17 02:25:44
回答 1查看 42关注 0票数 0

我知道这是一个很常见的问题,但我找不到一个解释,所以我尝试使用documentation示例

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

代码语言:javascript
复制
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));

我已经输出了我的final_urlparams变量,它们是正确的,但是除了Promise { pending }之外,我没有得到上面的任何东西。据我所知,第二个then解析Promise并将其传递给最终的then,后者应输出它。

我所做的是放入一些断点,并使用vscode遍历每个断点。我仍然能够看到承诺{ pending },但我不确定我如何才能找出问题所在。也许有一种方法可以更有效地使用调试器?任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-17 02:31:36

first then中似乎缺少return。你需要返回让它在第二个版本中可用。

每次当你这样做的时候,它都会为next创建一个承诺,让它像一个链一样被解析。因此,如果在中返回"something“,它将类似于返回Promise.resolve("something")

代码语言:javascript
复制
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
  })

示例:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61841642

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档