我有两个函数,这是异步和返回承诺,第一个的输出必须提供给第二个,这必须被包装在第三个函数。调用者模块调用第三个函数,而不必知道内部有两个函数。调用者代码能够捕获所有拒绝,但它不打印解析的值。
代码中有什么错误?
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时正确拒绝。
发布于 2018-02-08 10:03:08
这个问题是由getsecondfn引起的,因为你没有在其中返回一个Promise (这意味着caller函数上的then块不会触发)。
参考下面的固定demo:
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);
https://stackoverflow.com/questions/48676208
复制相似问题