使用 Promise 对象返回函数的值 [英] Returning a value of a function with Promise object

查看:31
本文介绍了使用 Promise 对象返回函数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 getWebContent 函数,该函数使用 Promise 返回网页的内容(我也在使用请求模块).

I am wring a getWebContent function that returns the content of a webpage using Promise (I am also using Request module).

我想使用这个函数的方式是var content = getWebContent(),这样content 变量就包含所请求网站的数据.我是这样开始的:

The way I'd like to use this function is var content = getWebContent(), so that content variable contains the data of the requested website. I started as follows:

var request = require('request')

var getWebContent = function () {
    
    target = 'http://www.google.com';
    var result = null;
    var get = function (url) {
        return new Promise(function (resolve, reject) {
            function reqCallback(err, res, body) {
                if (err) reject(err);
                else resolve(body);
            };
            request(url, reqCallback);
        });
    };

    get(target).then(function (res) {
        result = res;
        console.log(res);
    });
    
    return result;
};

var goog = getWebContent();
console.log(goog)

但是,这段代码不起作用,因为在解析 Promise 对象之前,该函数返回了 result 变量,该变量为 null.你能告诉我我应该如何修复我的代码以使其按预期工作吗?

However, this code does not work, because the function returns result variable, which is null, before the Promise object is resolved. Could you please let me know how I should fix my code so that it works as intended?

推荐答案

无论如何你都需要使用 Promise.Javascript 中的异步操作无法产生同步结果.

You need to use Promise anyway. You cannot make a synchronous result out of an asynchronous operation in Javascript.

var request = require('request')

var getWebContent = function () {

    target = 'http://www.google.com';
    var result = null;
    var get = function (url) {
        return new Promise(function (resolve, reject) {
            function reqCallback(err, res, body) {
                if (err) reject(err);
                else resolve(body);
            };
            request(url, reqCallback);
        });
    };

    return get(target);
};

var goog = getWebContent().then(function (res) {
  console.log(goog);  
});

这篇关于使用 Promise 对象返回函数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆