我有一个这样的javascript代码:

function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();

我总是得到一个未定义的值的var测试。我认为这是因为承诺还没有解决..有一种方法从承诺返回一个值?


当前回答

解决承诺后,你无法返回价值。而是在promise被解析时调用另一个函数:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

其他回答

当你从then()回调返回一些东西时,这有点神奇。如果返回一个值,则使用该值调用next then()。但是,如果返回一些类似承诺的东西,则next then()将等待它,并且仅在承诺解决(成功/失败)时调用。

来源:https://web.dev/promises/ queuing-asynchronous-actions

我在这里所做的是从justTesting函数返回一个承诺。然后,在解析函数时就可以得到结果。

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

希望这能有所帮助!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }

解决承诺后,你无法返回价值。而是在promise被解析时调用另一个函数:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

我更喜欢使用“await”命令和async函数来消除承诺的混淆,

在这种情况下,我会先写一个异步函数, 这将用来代替“promise”下调用的匿名函数。那么“这个问题的一部分是:

async function SubFunction(output){

   // Call to database , returns a promise, like an Ajax call etc :

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Return :
   return response;

}

然后从main function调用这个函数:

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

注意,这里我将主函数和子函数都返回给异步函数。

您需要使用引用数据类型,如数组或对象。

function foo(u,n){
  let result = [];
  const userBrands = new Promise((res, rej)=> {
                        res(['brand 1', 'brand 3']);
                      })
  
  userBrands.then((ub)=>{
    return new Promise((res, rej) =>{
      res([...ub, 'brand 4', 'brand 5']);
    })
  }).then(response => {
    return result.push(...response);
  });
  return result;
};
foo();