从承诺返回然后()

Pri*_*scy 92 javascript promise

我有一个像这样的JavaScript代码:

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

var test = justTesting();
Run Code Online (Sandbox Code Playgroud)

对于var测试,我总是有一个未定义的值.我认为这是因为承诺没有解决喷射......有没有办法从承诺中返回一个价值?

c0m*_*ing 117

当你从then()回调中返回一些东西时,它有点神奇.如果返回一个值,则使用该值调用next then().但是,如果你返回类似promise的东西,那么next()会等待它,并且仅在该promise承诺(成功/失败)时被调用.

通过https://developers.google.com/web/fundamentals/getting-started/primers/promises#queuing_asynchronous_actions

  • 有意思,兄弟。没有回答这个问题。 (11认同)
  • 但是 Promise.all 如何捕获每个已解决的 Promise 的返回值? (3认同)

jfr*_*d00 48

要使用承诺,您必须调用创建承诺的函数或者您必须自己创建承诺.你并没有真正描述你真正试图解决的问题,但是你要自己创建一个承诺:

function justTesting(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

justTesting(29).then(function(val) {
   // you access the value from the promise here
   log(val);
});

// display output in snippet
function log(x) {
    document.write(x);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您已经有一个返回promise的函数,则可以使用该函数并返回其promise:

// function that returns a promise
function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, t);
  });
}

function justTesting(input) {
  return delay(100).then(function() {
    return input + 10;
  });
}

justTesting(29).then(function(val) {
  // you access the value from the promise here
  log(val);
});

// display output in snippet
function log(x) {
  document.write(x);
}
Run Code Online (Sandbox Code Playgroud)

  • @RonRoyston - 首先,你传递给`.then()` 的函数是一个独立于包含函数的函数,所以当它被调用时,它有自己的返回值。其次,`.then()` 处理程序的返回值成为承诺的解析值。因此,`.then(val => {return 2*val;})` 将解析值从 `val` 更改为 `2*val`。 (3认同)
  • 让我失望的是双重“ return”,即“ justTesting”说“ return.then => return”。我知道我已经实现了这个功能(我已经实现了这个功能)(bcs linting迫使我离开了“ new Promise”),但是您能解释一下如何理解/思考那个收益/收益对吗? (2认同)

小智 9

我更喜欢使用“await”命令和异步函数来摆脱承诺的混乱,

In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :

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;

}
Run Code Online (Sandbox Code Playgroud)

and then I would call this function from main function :

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

   return lv_result + 1;
}
Run Code Online (Sandbox Code Playgroud)

Noting that I returned both main function and sub function to async functions here.


Vid*_*gla 8

我在这里做的是我从justTesting函数返回了一个promise.然后,您可以在解析函数时获得结果.

// 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);
  });
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 如果你想从 //do some with 输出返回一个值,你必须在 justTesing() 之前添加一个 return。例如,“ return justTesting().then((res) => { return res; }); (2认同)

Jos*_*ada 7

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

  • 是的。一旦你进入承诺空间,你就无法摆脱它。 (2认同)

Big*_*yes 6

Promises不“返回”值,它们将它们传递给回调(您使用 .then() 提供)。

它可能试图说你应该resolve(someObject);在承诺实现中做。

然后在您的then代码中您可以参考someObject做您想做的事情。