承诺和节点制作变量可用于不同的功能

时间:2017-06-13 08:49:32

标签: javascript node.js api variables promise

我有三个函数,我希望从函数一中创建变量,在函数三中创建两个函数。

功能一

函数一中的Bellow我试图将变量import scrapy from scrapy.spiders import XMLFeedSpider #from YahooScrape.items import YahooScrapeItem class Spider(XMLFeedSpider): name = "YahooScrape" allowed_domains = ["yahoo.com"] start_urls = ('https://feeds.finance.yahoo.com/rss/2.0/headline?s=BPMX',) #Crawl BPMX itertag = 'item' def parse_node(self, response, node): self.logger.info('Hi, this is a <%s> node!: %s', self.itertag, ''.join(node.extract())) item = {} item['title'] = node.xpath('title/text()',).extract_first() #define XPath for title item['link'] = node.xpath('link/text()').extract_first() item['pubDate'] = node.xpath('link/pubDate/text()').extract_first() item['description'] = node.xpath('description/text()').extract_first() #define XPath for description return item 包括在第三个函数中使用它。

emailUser

第二项功能

这个函数我试图传递var firstMethod = function() { var promise = new Promise(function(resolve, reject){ setTimeout(function() { app.post('/api/data', function (req, res) { console.log(req.body); var emailUser = req.body.email; res.send(emailUser); }); console.log('first method completed'); resolve({data: emailUser }); }, 2000); }); return promise; }; 以便在第三个函数中使用。

api_key

第三项功能

这个函数我想从函数一和二中访问变量。我已经包含了一个控制台日志,以便我可以看到我的控制台上打印的变量。

我还想访问这些函数以用于第三个函数/方法。

var secondMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            nodePardot.PardotAPI({
                userKey: 34535345,
                email: fsf@dd.com,
                password: fd3sv34f,
                DEBUG: true
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    console.error("Authentication Failed", err)
                } else {
                    // Authentication successful
                    var api_key = client.apiKey;
                    console.log("Authentication successful !", api_key);
                }
            });
            console.log('second method completed');
            resolve({newData: api_key});
        }, 2000);
    });
    return promise;
};

3 个答案:

答案 0 :(得分:1)

当API调用得到响应时,您需要在函数体内部解析。

var firstMethod = function() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            app.post('/api/data', function (req, res) {
                console.log(req.body);
                var emailUser = req.body.email;                            
                res.send(emailUser);

                //resolve when get the response
                resolve({data: emailUser });
            });

        }, 2000);
    });
    return promise;
};

您必须在出错时解决或拒绝。在这里,我解决了错误并将api_key设置为empty

var secondMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            nodePardot.PardotAPI({
                userKey: 34535345,
                email: fsf@dd.com,
                password: fd3sv34f,
                DEBUG: true
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    console.error("Authentication Failed", err);
                    resolve({newData: ''});

                } else {
                    // Authentication successful
                    var api_key = client.apiKey;

                    console.log("Authentication successful !", api_key);
                    resolve({newData: api_key});
                }
            });

        }, 2000);
    });
    return promise;
};
function thirdMethod(result) {
  console.log('show both functions', result[0].data, result[1].newData);
};

Promise.all([firstMethod(), secondMethod()])
.then(thirdMethod);

供参考

var firstMethod = function() {
    var promise = new Promise(function(resolve, reject) {
        setTimeout(function() {

            //resolve when get the response
            resolve({
                data: "a"
            });
        });

    }, 2000);

    return promise;
};

var secondMethod = function() {
    var promise = new Promise(function(resolve, reject) {
        setTimeout(function() {

            //resolve when get the response
            resolve({
                data: "b"
            });
        });

    }, 2000);

    return promise;
};

var thirdMethod = function(result) {
    console.log(result[0].data, result[1].data);
};

Promise.all([firstMethod(), secondMethod()]).then(thirdMethod);

<强>输出: a b

答案 1 :(得分:0)

你的第一个承诺解决了

{data: emailUser }

因此,第二个承诺中的somestuff将是

在你的第二种方法中,你可以解决

{data: somestuff.data, newData: api_key}

然后可以编写第三种方法

var thirdMethod= function(values) {

它将拥有前两个承诺的数据

总的来说,您的代码可以编写(ES2016 +)

var firstMethod = () => new Promise((resolve, reject) => setTimeout(() => app.post('/api/data', (req, res) => {
    console.log(req.body);
    var emailUser = req.body.email;
    res.send(emailUser);
    resolve({ emailUser });
}), 2000));

var secondMethod = ({ emailUser }) => new Promise((resolve, reject) => setTimeout(() => nodePardot.PardotAPI({
    userKey: 34535345,
    email: 'fsf@dd.com',
    password: 'fd3sv34f',
    DEBUG: true
}, (err, client) => {
    if (err) {
        // Authentication failed
        console.error("Authentication Failed", err);
        reject(err);
    } else {
        // Authentication successful
        var api_key = client.apiKey;
        console.log("Authentication successful !", api_key);
        resolve({ emailUser, api_key });
    }
}), 2000));

var thirdMethod = ({ emailUser, api_key }) => new Promise((resolve, reject) => setTimeout(() => {
    console.log('show both functions', emailUser, api_key);
    resolve('done');
}, 3000));

firstMethod().then(secondMethod).then(thirdMethod);

答案 2 :(得分:0)

首先,您需要修复firstMethodsecondMethod。在firstMethod中,emailUser变量仅在回调函数中设置,在您尝试使用它来解析承诺时,它不存在。您需要在回调中移动promise promise。

同样在secondMethod中,变量api_key仅存在于回调中,并且仅在函数成功时才存在。您需要在该回调中调用resolve()reject(),并移除外部的resolve()

完成后,您应该使用正确的值解析这两个承诺,您的代码可以是:

function thirdMethod([emailUSer, api_key]) {
  console.log('show both functions', emailUser, api_key);
};

Promise.all([firstMethod(), secondMethod()])
.then(thirdMethod);

请注意,由于thirdMethod仅由then()调用,因此除非您有异步操作,否则不需要创建Promise:它返回的任何内容都将自动换行Promise为你。