Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-fetch only returning promise pending

I am trying out node-fetch and the only result I am getting is:

Promise { <pending> }

How can I fix this so I get a completed promise?

code:

var nf = require('node-fetch');

nf(url).then(function(u){console.log(u.json())})
like image 961
Liondancer Avatar asked Dec 12 '16 23:12

Liondancer


People also ask

Does node fetch return a promise?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.

How do I resolve a promise pending issue?

The promise will always log pending as long as its results are not resolved yet. You must call . then on the promise to capture the results regardless of the promise state (resolved or still pending): Promises are forward direction only; You can only resolve them once.

Why is my asynchronous function returning promise pending instead of a value?

async functions always return promises. you need to await to get the value. run() var result = data // How to assign resultant value to another variable? no, it won't output what you want to myVar , because run is marked async , so it returns a Promise .

What is the difference between fetch and promise?

Fetch is another API that enables you to make network requests and REST service calls, similar to jQuery's AJAX methods or the native XMLHttpRequest . The main difference is that the Fetch API uses promises, which has a cleaner and more concise syntax that helps you avoid callback hell.


1 Answers

The problem with your code is that u.json() returns a promise

You need to wait for that new Promise to resolve also:

var nf = require('node-fetch');

var url = 'https://api.github.com/emojis'

nf(url).then(
  function(u){ return u.json();}
).then(
  function(json){
    console.log(json);
  }
)

For real code you should also add a .catch or try/catch and some 404/500 error handling since fetch always succeeds unless a network error occurs. Status codes 404 and 500 still resolve with success

like image 98
stujo Avatar answered Sep 19 '22 18:09

stujo