[英]Returning promise data to the calling function
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的得到的結果?
let callingFunction = function() {
return func1().then((res) => {
console.log("result",res)
return res
})
}
callingFunction().then((res) => {
let finalData = res
})
問題是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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.