我有一个这样的javascript代码:

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

var test = justTesting();

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


当前回答

我认为最初的海报想要的是从一个承诺返回一个未包装的值,而不实际返回另一个承诺。除非另有证明,否则恐怕这在then()或async/await上下文之外是不可能的。无论如何,你总能得到承诺。

其他回答

解决承诺后,你无法返回价值。而是在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();

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

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();

我在这里所做的是从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 :)
    }

承诺不会“返回”值,而是将值传递给回调(你可以用.then()提供)。

它可能会说你应该执行resolve(someObject);在承诺实现的内部。

然后在你的Then代码中,你可以引用someObject来做你想做的事情。

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

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