简体   繁体   English

许诺不适用于node.js

[英]promise is not working on node.js

I have try following code but it's not working well I put logger in both method to check which method execution finish but call addPersonalData method as per logger. 我尝试下面的代码,但是工作不佳,我将logger放在这两种方法中,以检查哪个方法执行完成,但是按照logger调用addPersonalData方法。

var promisePersonal = removePersonalData(profile);
promisePersonal.then(
    addPersonalData(personal, profile)
);

function removePersonalData(profile) {
    return new Promise(function(resolve, reject) {
        var id = profile._id;
        Personal.remove({
            parent_id: id
        }, function(error) {
            if (!error) {
                logger.info('Personal Remove : success');
                resolve(profile);
            } else {
                logger.error('Personal Remove : error' + error);
                reject(error);
            }
        });
    });
}

Logger : 记录器:

12: 22: 45 PM - info: Inside addPersonalData mothod <----- //here is problem
12: 22: 45 PM - info: Profile saved: addPersonalData
12: 22: 45 PM - info: Enter into removeEducationData
12: 22: 45 PM - info: Number of Education data::2
12: 22: 45 PM - info: Inside addEducationData mothod
12: 22: 45 PM - info: Personal Remove: success <---- //here is problem this should be first execute
12: 23: 10 PM - info: Education Remove: success

what I make mistake in above code ? 我在上面的代码中犯了什么错误? please give me your valuable advice to fix this. 请给我您的宝贵建议以解决此问题。

There is everything ok with Promise s you just using it wrong. Promise您的所有要求,而您只是错误地使用了它。 Try this: 尝试这个:

var promisePersonal = removePersonalData(profile);
promisePersonal.then(function(profile) { 
    addPersonalData(personal, profile);
});

function removePersonalData(profile) {
    return new Promise(function(resolve, reject) {
        var id = profile._id;
        Personal.remove({
            parent_id: id
        }, function(error) {
            if (!error) {
                logger.info('Personal Remove : success');
                resolve(profile);
            } else {
                logger.error('Personal Remove : error' + error);
                reject(error);
            }
        });
    });
}

Please change the code as below. 请如下更改代码。 Hope it will help. 希望它会有所帮助。

promisePersonal.then(
  () => addPersonalData(personal, profile) // callback function
)

Reason: Promise.then accepts a function but you have supplied a function call. 原因:Promise.then接受一个函数,但是您提供了一个函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM