为什么我不能Error在catch回调中抛出一个内部并让进程处理错误,就好像它在任何其他范围内一样?
如果我什么都不做console.log(err)就会被打印出去,我对发生的事情一无所知.这个过程刚刚结束......
例:
function do1() {
return new Promise(function(resolve, reject) {
throw new Error('do1');
setTimeout(resolve, 1000)
});
}
function do2() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('do2'));
}, 1000)
});
}
do1().then(do2).catch(function(err) {
//console.log(err.stack); // This is the only way to see the stack
throw err; // This does nothing
});
Run Code Online (Sandbox Code Playgroud)
如果回调在主线程中执行,为什么Error会被黑洞吞噬?
我正在运行外部代码作为node.js服务的第三方扩展.API方法返回promise.已解决的承诺意味着该操作已成功执行,失败的承诺意味着执行该操作存在一些问题.
现在这里我遇到了麻烦.
由于第三方代码未知,可能存在错误,语法错误,类型问题,任何可能导致node.js抛出异常的事情.
但是,由于所有代码都包含在promises中,因此这些抛出的异常实际上是作为失败的promise而返回的.
我试图将函数调用放在try/catch块中,但它从未被触发:
// worker process
var mod = require('./3rdparty/module.js');
try {
mod.run().then(function (data) {
sendToClient(true, data);
}, function (err) {
sendToClient(false, err);
});
} catch (e) {
// unrecoverable error inside of module
// ... send signal to restart this worker process ...
});
Run Code Online (Sandbox Code Playgroud)
在上面的伪代码示例中,当抛出错误时,它会在失败的promise函数中出现,而不是在catch中.
从我读到的,这是一个功能,而不是一个问题,与承诺.然而,我无法解决为什么你总是想要处理异常和预期的拒绝完全一样.
一个案例是关于代码中的实际错误,可能是不可恢复的 - 另一个是可能缺少配置信息,参数或可恢复的东西.
谢谢你的帮助!
WebDriverJS和Protractor本身完全基于承诺的概念:
WebDriverJS(以及Protractor)API完全是异步的.所有功能都返回承诺.WebDriverJS维护一个待处理的承诺队列,称为控制流,以保持执行的有序性.
并且,根据定义:
promise是一个表示值的对象,或者是值的最终计算.每个承诺都以挂起状态开始,可以使用值成功解析,也可以拒绝指定错误.
关于承诺拒绝的最后一部分是我不完全理解并且未在Protractor中处理过的事情.我们看到和编写的一种常见模式是使用then()并为成功解决的承诺提供功能:
element(by.css("#myid")).getAttribute("value").then(function (value) {
// do smth with the value
});
Run Code Online (Sandbox Code Playgroud)
问题:
是否有可能由任何Protractor/WebDriverJS函数返回的承诺无法成功解决并被拒绝?我们真的应该担心并处理它吗?
我看过很多实现,它们看起来都很不一样,我无法真正提炼出承诺的本质.
如果我不得不猜测它只是一个在回调触发时运行的函数.
有人可以在几行代码中实现最基本的承诺.
例如,从这个答案
片段1
var a1 = getPromiseForAjaxResult(ressource1url);
a1.then(function(res) {
append(res);
return a2;
});
Run Code Online (Sandbox Code Playgroud)
如何传递函数以then了解何时运行.
也就是说,它如何传递回ajax在完成时触发的回调代码.
片段2
// generic ajax call with configuration information and callback function
ajax(config_info, function() {
// ajax completed, callback is firing.
});
Run Code Online (Sandbox Code Playgroud)
这两个片段有何关联?
猜测:
// how to implement this
(function () {
var publik = {};
_private;
publik.then = function(func){
_private = func;
};
publik.getPromise = function(func){
// ??
};
// ??
}())
Run Code Online (Sandbox Code Playgroud) 我正在编写一个JavaScript函数,它发出HTTP请求并返回结果的承诺(但这个问题同样适用于基于回调的实现).
如果我立即知道为函数提供的参数是无效的,那么函数应该是throw同步的,还是应该返回一个被拒绝的promise(或者,如果你愿意的话,调用一个Error实例的回调)?
异步函数应始终以异步方式运行,特别是对于错误条件,这有多重要?是否确定throw,如果你知道程序是不是一个合适的状态的异步操作继续进行?
例如:
function getUserById(userId, cb) {
if (userId !== parseInt(userId)) {
throw new Error('userId is not valid')
}
// make async call
}
// OR...
function getUserById(userId, cb) {
if (userId !== parseInt(userId)) {
return cb(new Error('userId is not valid'))
}
// make async call
}
Run Code Online (Sandbox Code Playgroud) 承诺使用的模式仍然让我困惑.
例如,在Angular应用程序中,我有一个usersService带方法的服务emailExists(email).显然,它会向服务器执行请求,以检查给定的电子邮件是否已存在.
它感觉自然对我来说,使该方法emailExists(email)返回的承诺,在正常操作解析为true或false.如果我们只有一些意外错误(例如,服务器返回500: internal server error,则应拒绝承诺,但在正常操作中,它将被解析为相应的布尔值.
Hovewer,当我开始实现我的异步验证器指令(by $asyncValidators)时,我发现它想要解析/拒绝承诺.所以,到现在为止,我最终得到了这个相当丑陋的代码:
'use strict';
(function(){
angular.module('users')
.directive('emailExistsValidator', emailExistsValidator);
emailExistsValidator.$inject = [ '$q', 'usersService' ];
function emailExistsValidator($q, usersService){
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.emailExists = function(modelValue, viewValue){
return usersService.emailExists(viewValue)
.then(
function(email_exists) {
// instead of just returning !email_exists,
// we have to perform conversion from true/false
// to resolved/rejected promise
if (!email_exists){
//-- email does not …Run Code Online (Sandbox Code Playgroud) 我目前正在实现一个基于PDF.js的PDF查看器,作为我了解promise对象的一部分.
我还了解到调试控制台中不会自动显示运行时错误:
PDFJS.getDocument(...).then(
function(pdfDocument){
alert(UndefinedVariable); // Not shown in console!
},
function(error){
console.log("Error occurred", error);
}
);
Run Code Online (Sandbox Code Playgroud)
除了.done()在http://www.asyncdev.net/2013/07/promises-errors-and-express-js/中描述的添加之外,我还没有找到在promise函数中显示运行时错误的漂亮方法.(这对PDF.js不起作用)或添加.catch(function(error){ console.error(error); }).
我知道我可以在调试器中打破运行时错误的异常,但是我也可以通过这样做来打破其他异常(在jQuery中),这意味着我必须在每个页面加载时执行5个jQuery异常,然后我才能检查我自己的代码是否包含运行时错误.
有没有办法强制promise函数像正常一样记录运行时错误(没有为每个函数调用编写额外的代码)?
我正在使用AWS JS SDK提供的承诺.当我创建包装AWS SDK的异步函数时,我正在做的事情的主旨如下所示:
module.exports.myCustomFunction = input => {
if (badInput) {
throw new Error('failed') // <-- This is they key line
}
return sns.createTopic(someParams).promise()
}
// The caller looks like this:
myModule.myCustomFunction(someInput).then(result => {
// carry on
})
.catch(err => {
// do something with the error
})
Run Code Online (Sandbox Code Playgroud)
有人说我不应该在这些基于承诺的函数中抛出错误.他们建议返回Promise.reject('failed').说实话,我不是那么精通承诺,所以他们的解释有点过了我的脑袋.
javascript ×8
promise ×7
asynchronous ×2
node.js ×2
angularjs ×1
api-design ×1
es6-promise ×1
protractor ×1
selenium ×1
testing ×1
throw ×1