【问题标题】:Q Promise resolve/reject logic - why isn't promise returned as rejected?Q Promise 解决/拒绝逻辑 - 为什么没有将 Promise 作为拒绝返回?
【发布时间】:2016-06-10 12:12:09
【问题描述】:

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

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();
	})
} )();

【问题讨论】:

  • Reject 不会在 Promise 中返回”是什么意思? catch 回调不会执行吗?

标签: javascript node.js promise q


【解决方案1】:

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

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

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

编辑:

我又看了一下代码,结果是这样的——被拒绝的 promise 被捕获了:

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

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

【讨论】:

  • 谢谢。是的,你说得对,是别的东西让它看起来不拒绝——归结为我缺乏理解。这是我没有得到的:
  • 1) 我希望看到“错误获取 IBdata”返回并显示在某处,为什么没有呢?
  • 3) 所有错误都会被捕获,但是您可以完全删除else { reject("error getting insight"); },并且您会得到与它存在时相同的结果,那么有什么意义呢?
  • 如果您在拒绝之前的 'else' 中使用 console.log('show me'),它不会被记录到控制台 - 例如 if (insight){ resolve(insight); // State will be fulfilled } else { reject("error getting insight"); }。为什么不呢?
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2020-09-17
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2020-01-02
相关资源
最近更新 更多