我有一个逻辑试图在返回承诺rp
的过程中在 if-else 之后运行(请求承诺) 。then
根据我的假设,我认为该过程应该经过第 1 步到第 10 步(某些部分可能会重复并增加价值)。完成后solveProblem
,最后,它转到doOther()
.
以下是我的代码的简化版本,尽管它有点乱:
const request = require("request");
const rp = require("request-promise");
let url = "http://localhost:3000/";
let sendResult = c => {
console.log("step 4", c);
return new Promise((resolve, reject) => {
if (c < 5) {
console.log("step 5 resolve(true)", c);
resolve(true);
} else {
console.log("step 5 resolve(false)", c);
resolve(false);
}
});
};
let repeat = (a, b) => {
c = a + b;
console.log("step 3", c);
return sendResult(c).then(result => {
console.log("step 6", result);
if (!result) {
console.log("step 7");
rp(url).then(data => {
console.log("step 8");
let d = c + 1;
if (d < 7) {
console.log("step 9", d);
return repeat(d, a);
} else {
console.log("step 10", d);
return "done";
}
});
} else {
return repeat(c, a);
}
});
};
let solveProblem = (a, b) => {
return new Promise((resolve, reject) => {
resolve(a + b);
});
};
let doOther = () => {
console.log("doOther");
};
let run = (a, b) => {
console.log("step 1");
solveProblem(a, b)
.then(data => {
console.log("step 2", data);
return repeat(data, 1);
})
.then(() => {
return doOther();
});
};
run(1, 1);
然而,结果并不如我所料。它推迟了rp
,直接跳到另一个外面再到doOther()
。之后,它继续rp
。像这样:
step 1
step 2 2
step 3 3
step 4 3
step 5 resolve(true) 3
step 6 true
step 3 5
step 4 5
step 5 resolve(false) 5
step 6 false
step 7
doOther
step 8
step 9 6
step 3 9
step 4 9
step 5 resolve(false) 9
step 6 false
step 7
step 8
step 10 10
我确定这是异步问题,但我不确定如何修改它以符合我的要求(然后是第 1~10 步doOther()
)。谁能帮我弄清楚?谢谢。