我正在尝试承诺链接,但我不太明白。我正在做这个练习,我必须做以下场景:
“你在恶作剧一个办公室成员,在他的咖啡里加盐,你要用/locate
api检查他的位置,'locate'可以是以下之一:
response.body: 'in the office'
response.body: 'in the kitchen'
你只在他在厨房的时候加盐,所以如果 response.body 返回“在厨房”,你用另一个post api 给他的咖啡加盐/addSalt
。
现在有本练习中的最终 api 端点,称为/run
在满足任一条件时调用它的位置:
/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
。这显然不起作用,但它可以帮助概述我想要得到的东西。任何提示?
myPromiseFunction() 应该解析一个包含“in the office”或“in the kitchen”的对象,该对象将传递给conditionalChaining的值进行处理,并确定下一个动作。请参阅下面的示例,我已针对您的用例进行了调整。
function locate() {
//const msg = "in the office"; // choose either one to return, can comment the other out.
const msg = "in the kitchen";
var obj = {body: msg};
return Promise.resolve(obj);
}
function addSalt(salt) {
console.log("addSalt");
return Promise.resolve("We added salt");
}
function run() {
console.log("We are running");
return Promise.resolve("Running");
}
function conditionalChaining(value) {
if (value.body === 'in the kitchen') {
//do addSalt then run
return addSalt("some salt value since its undefined by u").then(run);
} else if ( value.body === 'in the office' ) {
console.log("hey you are in the office");
} else {
//run
return run();
}
}
// in this function, you are suppose to resolve the string "in the kitchen" or "in the office"
// this is so that the conditionalChaining function takes in either of the string and process the next action.
function myPromiseFunction() {
return Promise.resolve(locate());
}
myPromiseFunction().then(conditionalChaining).then(function () {
console.log("All done!");
});
jsfiddle:https ://jsfiddle.net/y7xrw6d0/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句