Javascript 从承诺返回 then()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34094806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:54:42  来源:igfitidea点击:

Return from a promise then()

javascriptpromise

提问by Priscy

I have got a javascript code like this:

我有一个这样的javascript代码:

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

var test = justTesting();

I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?

我的 var 测试总是有一个未定义的值。我认为这是因为承诺还没有解决……有没有办法从承诺中返回一个值?

回答by c0ming

When you return something from a then()callback, it's a bit magic. If you return a value, the next then()is called with that value. However, if you return something promise-like, the next then()waits on it, and is only called when that promise settles (succeeds/fails).

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

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

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

回答by jfriend00

To use a promise, you have to either call a function that creates a promise or you have to create one yourself. You don't really describe what problem you're really trying to solve, but here's how you would create a promise yourself:

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

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

Or, if you already have a function that returns a promise, you can use that function and return its 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);
}

回答by Vidur Singla

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

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

Hope this helps!

希望这可以帮助!

// old answer

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

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

回答by beemaster

I prefer to use "await" command and async functions to get rid of confusions of promises,

我更喜欢使用“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 :

在这种情况下,我将首先编写一个异步函数,这将用于代替在此问题的“promise.then”部分下调用的匿名函数:

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;

}

and then I would call this function from main function :

然后我会从主函数调用这个函数:

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

   return lv_result + 1;
}

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

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