【发布时间】:2021-06-11 00:47:35
【问题描述】:
我正在尝试 Promise 链接,但我不太明白。我有这个练习我正在做的地方我必须做以下场景:
“你是在恶作剧办公室成员,在他的咖啡里加盐,你要通过/locate api查看他的位置,'locate'可以是以下任意一种:
response.body: 'in the office'
response.body: 'in the kitchen'
你只在他在厨房时加盐,所以如果 response.body 返回“在厨房里”,你就用/addSalt 的另一个 post api 给他的咖啡加盐。
现在这个练习中有一个名为 /run 的最终 api 端点,在满足任一条件时调用它:
/locate returns 'in the office'
/addSalt is called.
我在没有合并任何 api 或 json 的情况下尝试了以下操作(但我想这样做),它看起来像这样:
function myPromiseFunction() {
//Change the resolved value to take a different path
return Promise.resolve(true);
}
function conditionalChaining(value) {
if (value.body === 'in the kitchen') {
//do addSalt then run
return addSalt(salt).then(run);
} else {
//run
return run();
}
}
function locate() {
// fetch http get location, response body is either 'in his office' or 'in the kitchen'
return Promise.resolve(response.body);
}
function addSalt(salt) {
console.log("addSalt");
return Promise.resolve("We added salt");
}
function run() {
console.log("We are running");
return Promise.resolve("Running");
}
myPromiseFunction().then(conditionalChaining).then(function() {
console.log("All done!");
}).
catch(function(e) {
});
我不知道conditionalChaining 正在做什么,也不知道myPromiseFunction。这显然没有用,但它可以帮助概述我想要得到的东西。有什么建议吗?
【问题讨论】:
-
它不起作用,因为没有
response并且value没有body属性。
标签: javascript api promise