将promise数据返回给调用函数

时间:2018-02-21 11:32:49

标签: javascript promise

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中得到结果?

2 个答案:

答案 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);
  });