gpt4 book ai didi

javascript - 从 promise 处理程序返回 promise

转载 作者:行者123 更新时间:2023-12-01 02:27:03 24 4
gpt4 key购买 nike

我有两个异步函数并返回 promise ,第一个函数的输出必须提供给第二个函数,并且必须将其包装在第三个函数中。调用者模块调用第三个函数,并且不必知道内部有两个函数。调用者代码能够捕获所有拒绝,但不会打印解析值。

代码有什么问题吗?

function firstfn(x) {
return new Promise(function(resolve, reject) {
if (x === 0)
reject(new Error("not a valid num"));
else {
setTimeout(function() {
console.log("successfully resolving1");
resolve(x * 2);
}, 500);
}

});
}

function secondfn(y) {
return new Promise(function(resolve, reject) {
if (y === 100) reject(new Error("reject from 2"));
else {
setTimeout(function() {
console.log("successfully resolving2");
resolve(y + 2);
}, 500);
}

});
}

function getsecondfn(y) {
firstfn(y)
.then(function(response) {
return secondfn(response);
})
}

function caller(inp) {
getsecondfn(inp)
.then(res => {
console.log(res);
})
.catch(function(err) {
console.log(err);
})
}

caller(2);

上面的代码不会打印 6,但当值为 0 或 50 时会正确拒绝。

最佳答案

问题是由 getsecondfn 引起的,因为您没有在其中返回 Promise (意味着 thencaller 函数不会触发)。

请参阅下面的固定演示:

function firstfn(x) {
return new Promise(function(resolve, reject) {
if (x === 0)
reject(new Error("not a valid num"));
else {
setTimeout(function() {
console.log("successfully resolving1");
resolve(x * 2);
}, 500);
}

});
}

function secondfn(y) {
return new Promise(function(resolve, reject) {
if (y === 100) reject(new Error("reject from 2"));
else {
setTimeout(function() {
console.log("successfully resolving2");
resolve(y + 2);
}, 500);
}

});
}

function getsecondfn(y) {
return firstfn(y)
.then(function(response) {
return secondfn(response);
});
}

function caller(inp) {
getsecondfn(inp)
.then(res => {
console.log(res);
})
.catch(function(err) {
console.log(err);
})
}

caller(2);

关于javascript - 从 promise 处理程序返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676208/

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