【问题标题】:How can I use the value of the body outside this method?如何在此方法之外使用 body 的值?
【发布时间】:2018-10-28 15:56:18
【问题描述】:
var request = require('request');

var boardsCall = {
  method: 'GET',
  url: 'https://api.trello.com/1/organizations/xxxxxxxxxx/boards?filter=open&fields=id,name',
  qs: {
    key: 'xxxxxxxxxxxxxxxx',
    token: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
  }
};

function test(url, callback) {
  request(url, function(error, response, body) {
    if (error) {
      return callback(error);
    }
    callback(null, JSON.parse(body));
  })
}
const x = test(boardsCall, function(err, body) {
  if (err) {
    console.log(err);
  }
  else {
    return body;
  }
})

console.log(x);

如何使用body外面的值? 以后在其他方法中使用 我对任何更改的最佳实践持开放态度,我读了很多书,但对回调、承诺异步等待的话题有点困惑。

【问题讨论】:

    标签: node.js asynchronous callback request


    【解决方案1】:

    在我的方法中,请求用Promise 包装,测试函数返回 Promise 响应。在main方法里面会同步执行test函数。一旦分配给 x 的响应值,就会在 main() 方法中执行剩余的处理逻辑。

    var request = require('request');
    
    var boardsCall = {
      method: 'GET',
      url: 'https://api.trello.com/1/organizations/xxxxxxxxxx/boards?filter=open&fields=id,name',
      qs: {
        key: 'xxxxxxxxxxxxxxxx',
        token: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
      }
    };
    
    function test(url) {
        //Wrapping request callback with Promise
        return new Promise((res, rej)=> {
            request(url, function(error, response, body) {
                if (error) {
                  rej(error);
                }
                res(JSON.parse(body));
              })
        })
    }
    
    async function main() {
        try {
            const x = await test(boardsCall);       
            console.log("Result : ", x );
    
            // Remaining logic to process based on x value
    
        } catch(e) {
            console.error("Error :", e);
        }
    
    
    }
    
    //Calling main method
    main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2015-06-07
      • 2016-02-02
      相关资源
      最近更新 更多