【问题标题】:New Promise output returning the words "Promise { }"新的 Promise 输出返回单词“Promise { }”
【发布时间】:2018-10-19 20:37:27
【问题描述】:

我正在使用 Promise 编写代码以获取 JSON 值,该代码正在运行,但输出远离单词 Promise { } 之间返回。

const info = new Promise((resolve, reject) => {

    var req = require('request');


    var options = {
        url: 'https://api.info.com/',
        headers: {
            'User-Agent': 'request'
        }
    };
    req(options, function (err, response, body) {
        if (!err && response.statusCode === 200) {
            resolve(JSON.parse(body));

        }
    });
});
console.log(info); //Output: Promise { [ { name: 'Gary'}, { name: 'John'} ] }

我做错了什么?

我希望我的输出与网站上的一样:

[ { name: 'Gary'}, { name: 'John'} ]

==> 更新 它部分有效:

const info = new Promise((resolve, reject) => {

    var req = require('request');


    var options = {
        url: 'https://api.info.com/',
        headers: {
            'User-Agent': 'request'
        }
    };
    req(options, function (err, response, body) {
        if (!err && response.statusCode === 200) {
             resolve(JSON.parse(body));

         }
    });
});
info.then(function(value) {console.log(value)});//output: [ { name: 'Gary'}, { name: 'John'} ]

但是,我需要使用 then 之外的结果来使用这个 Json 结果执行其他查询操作,我尝试了类似的方法:

info.then(function(value) { jsonfile = value });
console.log(jsonfile);//Output: jsonfile is not defined

【问题讨论】:

  • 这是一个承诺;不确定您的期望——您是立即记录它而不是等待它。到它被记录的时候,它已经解决了,但是你正在注销 Promise 本身。
  • 你不能这样做,因为这是一个异步调用,如果你真的想要这种响应,请使用 await 关键字。geeksforgeeks.org/using-async-await-in-node-js

标签: json node.js promise


【解决方案1】:

你正在控制台记录承诺对象。如果您想要来自解析操作的数据,您可以链接使用该数据的函数。 例如:

const info = new Promise((resolve, reject) => {

    var req = require('request');


    var options = {
        url: 'https://api.info.com/',
        headers: {
            'User-Agent': 'request'
        }
    };
    req(options, function (err, response, body) {
        if (!err && response.statusCode === 200) {
            resolve(JSON.parse(body));

        }
    });
});
//On resolve, perform some function to the returned value (This can be replaced with a function call)
info.then(function(value) {console.log(value)});

更多示例和详细信息可以在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises找到

根据评论进行编辑(我没有发布 cmets 的代表):Promise 是同步的,而不在 Promise 或 then() 内的代码不会被同步处理。这是值得一提的,因为虽然你可以将你的值签名到全局变量或在承诺之前定义你的 var 'value','value' 可能还没有被承诺解决,这意味着你有引入了比赛条件。相反,如果您在另一个函数中需要来自您的 Promise 的数据(它们需要按顺序运行),则应该在您的 then() 中调用该函数。

例如:

info.then(function(value){
otherfunction(value);
});

function otherfunction(val) {
//does whatever you need to value and will occur after the promise above resolves
}

【讨论】:

  • 这很有用,但现在我不能在 then 之外使用 de var value:coinmarketinfo.then(function (value) { var data =价值 ); }); console.log(data);
  • 您需要将您的值存储在一个全局变量中(有关此方法的问题,请参阅我的答案)或链接您的新函数,以便它在承诺结束后执行。
【解决方案2】:

info 是一个未决的承诺。你需要await使用.then就可以了

示例代码

const info = new Promise((resolve, reject) => {

  var req = require('request');


  var options = {
    url: 'http://httpbin.org/get',
    headers: {
      'User-Agent': 'request'
    }
  };
  req(options, function (err, response, body) {
    if (!err && response.statusCode === 200) {
      resolve(JSON.parse(body));

    }
  });
});
console.log(info); // Promise { <pending> }
info.then((result) => console.log(result)); // api result

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多