NodeJS 获取承诺回调挂起 [英] NodeJS fetch promise callback pending

查看:30
本文介绍了NodeJS 获取承诺回调挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

fetch(url).then(response => {const json = response.json();console.log('最简单的获取', json, json.where);});

在控制台中我得到:

 最简单的获取 Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} undefined

大部分都会得到这个.有时我会获得成功"状态.对我来说,这意味着在 fetch 承诺解决之前正在运行回调.

我希望该函数仅在提取完成时运行.我该怎么做?

解决方案

response.json()返回一个promise,使用then回调来获取数据:><块引用>

Body mixin 的 json() 方法接受一个 Response 流并读取它完成.它返回一个承诺,该承诺将正文文本解析为 JSON.

fetch(url).then(response => response.json()).then(data => console.log('simplest possible fetch', data, data.where));

I have this code:

fetch(url).then(response => {
  const json = response.json();
  console.log('simplest possible fetch', json, json.where);
});

In the console I get:

simplest possible fetch Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} undefined

I get this most of the time. Sometimes I get the "success" status. To me this implies the callback is being run before the fetch promise has resolved.

I want the function to be run only when the fetch completes. How do I do this?

解决方案

response.json() returns a promise, use then callback to get the data:

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

fetch(url)
  .then(response => response.json())
  .then(data => console.log('simplest possible fetch', data, data.where));

这篇关于NodeJS 获取承诺回调挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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