node-fetch only returning promise pending

前端 未结 3 1949
终归单人心
终归单人心 2021-02-13 11:04

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

Promise { }

How can I fix this so I get a completed

相关标签:
3条回答
  • 2021-02-13 11:24

    u.json() returns a promise, so you'd need to do this

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

    or as you're using node

    nf(url).then(u => u.json()).then(j => console.log(j));
    
    0 讨论(0)
  • 2021-02-13 11:34

    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

    0 讨论(0)
  • 2021-02-13 11:34

    A promise is a mechanism for tracking a value that will be assigned some time in the future.

    Before that value has been assigned, a promise is "pending". That is usually how it should be returned from a fetch() operation. It should generally be in the pending state at that time (there may be a few circumstances where it is immediately rejected due to some error, but usually the promise will initially be pending. At some point in the future, it will become resolved or rejected. To get notified when it becomes resolved or rejected, you use either a .then() handler or a .catch() handler.

    var nf = require('node-fetch');
    
    var p = nf(url);
    
    console.log(p);   // p will usually be pending here
    
    p.then(function(u){
        console.log(p);     // p will be resolved when/if you get here
    }).catch(function() {
        console.log(p);     // p will be rejected when/if you get here
    });
    

    If it's the .json() method that has you confused (no idea given the unclear wording of your question), then u.json() returns a promise and you have to use .then() on that promise to get the value from it which you can do either of these ways:

    var nf = require('node-fetch');
    
    nf(url).then(function(u){
       return u.json().then(function(val) {
          console.log(val);
       });
    }).catch(function(err) {
        // handle error here
    });
    

    Or, with less nesting:

    nf(url).then(function(u){
       return u.json()
    }).then(function(val) {
          console.log(val);
    }).catch(function(err) {
        // handle error here
    });
    

    There is an exact code sample for this on the documentation page for node-fetch. Not sure why you did not start with that.

    0 讨论(0)
提交回复
热议问题