node-fetch only returning promise pending

前端 未结 3 1947
终归单人心
终归单人心 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: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.

提交回复
热议问题