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())})
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With