Q承诺解决/拒绝逻辑 - 为什么承诺不会被拒绝?

时间:2016-06-09 15:24:38

标签: javascript node.js promise q

承诺的新手,试图理解逻辑流程。以为我明白了,直到我开始插入错误进行测试。在下面的例子中,当我注释掉第3行时,为什么Reject不会在promise中返回?

var Q = require( "q" )

var getInstallBase = function() {
     return new Promise(function(resolve, reject) {	
	//var IBdata = 'temp IBdata'; // <------comment out so IBdata not defined
     if (IBdata){
            resolve(IBdata); // State will be fulfilled
        } else {
	    reject("error getting IBdata"); // State will be rejected			          
        }
     });
}

var mungeIt = function(IBdata){
    return new Q.Promise(function(resolve,reject){
		// get insight from data
		console.log('IBdata = ' + IBdata);
		var insight = 'temp insight';
        if (insight){
            resolve(insight); // State will be fulfilled
        } else {
            reject("error getting insight"); // State will be rejected
        }
    })
}

var postResults = function(insight) {
	return new Promise(function(resolve, reject) {
		console.log('insight = ' + insight);
		// post result
		var objectID = '12345';
		if (objectID){
			setTimeout(function() {
				console.log('done waiting');
				resolve(objectID);
			}, 2000);
			 // State will be fulfilled
		} else {
			reject("error posting insight to object store"); // State will be rejected
		}
	});
};

(function extractInsightCycle() {
	getInstallBase().then(mungeIt).then(postResults).then(function(objectID) {
		console.log('object successfully posted, ID: ' + objectID)
		extractInsightCycle();
	}).catch(function(error) {
		console.log('something went wrong', error);
		extractInsightCycle();
	})
} )();

1 个答案:

答案 0 :(得分:2)

请查看此JSBin:http://jsbin.com/zutotuvomo/edit?js,console

它包含代码的简化版本,如您所见,getInstallBase返回的承诺确实拒绝。

您的代码中可能还有其他内容使其看起来没有拒绝。

修改

我又看了一下代码,这就是发生了什么 - 被拒绝的承诺被抓住了:

function(error) {
    console.log('something went wrong', error);
    extractInsightCycle();
}

调用extractInsightCycle这是启动整个过程的函数,这会导致无限循环(实际上是无限递归)。