let func1 = function() {
return new Promise((resolve,reject) => {
let someVal = 5;
if (condition) {
resolve(someVal);
}
else {
reject('error occured');
}
});
}
let callingFunction = function() {
func1().then((res) => {
console.log("result",res); /* want to return res to the callingFunction */
return res; /* doesn't work as it returns to the .then not to the callingFunction I guess. */
});
}
let finalData = callingFunction();
将.then
承诺块的结果发送到callingFunction是否可行,以便在finalData中得到结果?
答案 0 :(得分:0)
let callingFunction = function() {
return func1().then((res) => {
console.log("result",res)
return res
})
}
callingFunction().then((res) => {
let finalData = res
})
答案 1 :(得分:0)
问题是promise是一个异步操作,因此let finalData = callingFunction();
计算为 undefined 。如果您想在callingFunction()
中使用promise的结果,只需将res
作为参数传递给它:
let func1 = function() {
return new Promise((resolve,reject) => {
let someVal = 5;
if (condition) {
resolve(someVal);
}
else {
reject('error occured');
}
});
}
func1().then((res) => {
console.log("result",res); /* want to return res to the callingFunction */
callingFunction(res);
});