Promise 和节点使变量在不同的函数中可用

问题描述 投票:0回答:3

我有三个函数,我希望使函数一和函数二中的变量在函数三中可用。

功能一

在函数一中我试图包含该变量

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: [email protected],
                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;
};

第三个功能

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

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

  var thirdMethod= function() {
    var promise = new Promise(function(resolve, reject){
 console.log('show both functions', emailUser, api_key);
        }, 3000);
    });
    return promise;
};
    
    firstMethod()
        .then(secondMethod)
        .then(thirdMethod);
javascript node.js variables promise
3个回答
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: [email protected],
                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


0
投票

首先您需要修复

firstMethod
secondMethod
。在
firstMethod
中,
emailUser
变量仅在回调函数内设置,在您尝试使用它来解决承诺的地方不存在。您需要在回调中移动承诺解析。

同样,在

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
中。


0
投票

你的第一个承诺得到解决

{data: emailUser }

因此

somestuff
第二个承诺就是这样

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

{data: somestuff.data, newData: api_key}

那么就可以写第三种方法了

var thirdMethod= function(values) {

它将拥有前两个 Promise 的数据

总体来说,你的代码是可以写的(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: '[email protected]',
    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);
© www.soinside.com 2019 - 2024. All rights reserved.