gpt4 book ai didi

javascript - 在 Promise 解析器中捕获错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:41:26 25 4
gpt4 key购买 nike

我无法捕获 Resolve promise 中发生的异常/错误。有人可以解释是否有办法捕获此错误:

createAsync = function() {
var resolve, reject,
promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
};

promise = createAsync()
promise.then(function myresolver(){
throw Error('wow')
})


// Catching the error here
try {
promise.resolve()
} catch(err) {
console.log( 'GOTCHA!!', err );
}

编辑:

让我更好地解释一下,我正在尝试创建一个 API,而用户只能访问 promise 解决/拒绝部分:

// This is my API user does not have access to this part
promise = createAsync()
promise
.then(function(fun) {
if (typeof fun != 'function')
throw Error('You must resolve a function as argument')
}).catch(function(err){
// Some internal api tasks...
return Promise.reject(err)
})

现在我想给他的解决方案,但不起作用:

// Here is where the user can resolve the promise.
// But must be able to catch the error
promise.catch(function(err){
console.log("GOTCHA", err)
})
promise.resolve('This must be a function but is a string');

有什么想法吗?


更多信息:Yes 是常见用法的反模式。这是一个远程过程调用 API,因此用户必须能够拒绝或解决。而且调用是异步的,所以最好的方法是使用 promises。我不会说是这种情况的反模式。实际上是唯一的模式。 (我不能使用异步/等待)

最佳答案

Let me explain me better, I'm trying to create an API and the user only have access to the promise resolve/reject part. Now the solution I would like to give him does not work. Any ideas?

不要将所有内容都放在初始的 promise 对象上。听起来您真正需要向用户公开的是 a) 一种解决方法(包括拒绝)和 b) 一种取回结果( promise )的方法。所以你需要做的就是给他一个函数:

function createAsync() {
var resolve;
var promise = new Promise(function(r) { resolve = r; })
.then(function(fun) {
if (typeof fun != 'function')
throw Error('You must resolve a function as argument')
}).catch(function(err){
// Some internal api tasks...
throw err;
});
return function(value) {
resolve(value);
return promise;
};
}

他会像这样使用它

var start = createAsync();
// possibly later
start('This must be a function but is a string').catch(function(err){
console.log("GOTCHA", err)
});
// or
start(Promise.reject(new Error('doomed to fail'))).catch(…);

但实际上这个模式仍然很复杂。只需给您的 createAsync 函数一个参数(如果用户需要延迟传递 fun,它可能会收到一个 promise )并完成它:

function createAsync(valu) {
return Promise.resolve(val).then(function(fun) {
if (typeof fun != 'function')
throw Error('You must resolve a function as argument')
}).catch(function(err){
// Some internal api tasks...
throw err;
});
}

createAsync('This must be a function but is a string').catch(function(err) {
console.log("GOTCHA", err)
});
// or
createAsync(new Promise(function(resolve) {
// later
resolve('This must be a function but is a string');
})).catch(function(err) {
console.log("GOTCHA", err)
});

关于javascript - 在 Promise 解析器中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41254636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com