简体   繁体   English

试图理解 new Promise 和 Async/await

[英]Trying to understand between new Promise and Async/await

I have a very basic question:我有一个非常基本的问题:

This code这段代码

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

gives this output, which is correct:给出这个输出,这是正确的:

> "calling"
> "resolved"

This one however:然而这个:

async function resolveAfter2Seconds() {
    setTimeout(() => {
      return 'resolved';
    }, 2000);
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

It gives instead:它改为:

> "calling"
> undefined

From javascript.info:来自 javascript.info:

The word “async” before a function means one simple thing: a function always returns a promise.函数前的“异步”一词意味着一件简单的事情:函数总是返回一个承诺。 Other values are wrapped in a resolved promise automatically.其他值自动包装在已解决的承诺中。 So, async ensures that the function returns a promise, and wraps non-promises in it因此,异步确保函数返回一个承诺,并在其中包装非承诺

So there's something I am misunderstanding, isn't the resolveAfter2Seconds returning a promise in both scenarios (the resolveAfter2Seconds in the 2nd scenario has async)?所以我有一些误解,resolveAfter2Seconds 是不是在两种情况下都返回了一个承诺(第二种情况下的 resolveAfter2Seconds 是异步的)? If so why the output in the 2nd scenario?如果是这样,为什么第二个场景中的输出?

In the second case, you are not returning anything from the resolveAfter2Seconds function, the return in the code is for the callback of the setTimeout , which will not be returned by the resolveAfter2Seconds function.在第二种情况下,您没有从resolveAfter2Seconds函数返回任何内容,代码中的返回用于setTimeout的回调, resolveAfter2Seconds函数不会返回该resolveAfter2Seconds Hence the undefined .因此undefined

Its a pretty basic beginner mistake you use return in an callback and expect to recevive something from the parent function这是一个非常基本的初学者错误,您在回调中使用return并期望从父函数中获得一些东西

This here:这里:

async function resolveAfter2Seconds() {
    setTimeout(() => {
      return 'resolved';
    }, 2000);
}

Can be written to this here:可以写到这里:

async function resolveAfter2Seconds() {
    setTimeout(function() {
      return 'resolved';
    }, 2000);
}

And as you can see there is a second function and you return resolved to your callback function.正如你可以看到有第二个功能,并返回resolved您的回调函数。 There is actually no way to return this value like you want to, you will need to use Promises like in your first example实际上没有办法像你想要的那样返回这个值,你需要像在你的第一个例子中一样使用 Promises

Since resolveAfter2Seconds doesnt return anything it will return by default undefined由于resolveAfter2Seconds不返回任何内容,因此默认情况下将返回undefined

No return = returns undefinedreturn = 返回undefined

Both functions are returning a promise, the main differences between the two are when each promise resolves and what each promise resolves to.这两个函数都返回一个 promise,两者的主要区别在于每个 promise 何时解析以及每个 promise 解析为什么。 In your second function resolveAfter2Seconds , you're only returning inside of the setTimeout function, and as a result, you return back to the caller of the setTimeout callback function, not your resolveAfter2Seconds .在您的第二个函数resolveAfter2Seconds ,您只在 setTimeout 函数内部返回,因此,您返回给 setTimeout 回调函数的调用者,而不是您的resolveAfter2Seconds Rather, your resolveAfter2Seconds doesn't return anything, and so it will implicitly return undefined which gets wrapped within a promise.相反,您的resolveAfter2Seconds不返回任何内容,因此它将隐式返回undefined ,它被包装在一个承诺中。 It is more or less the same as writing:它或多或少与写作相同:

function resolveAfter2Seconds() {
    setTimeout(() => {
      return 'resolved';
    }, 2000);
      
    return Promise.resolve(undefined);
}

 function resolveAfter2Seconds() { setTimeout(() => { return 'resolved'; }, 2000); return Promise.resolve(undefined); // returns a promise which resolves with the value of `undefined` } async function asyncCall() { console.log('calling'); const result = await resolveAfter2Seconds(); console.log(result); // expected output: "resolved" } asyncCall();

The above returns a Promise which resolves immediately with the value of undefined .以上返回一个 Promise ,它立即使用undefined的值解析。 As a result, you either need to explicitly wrap your setTimeout in a promise and resolve() (like your first resolveAfter2Seconds ), or use something like a helper sleep method:因此,您要么需要将您的 setTimeout 显式包装在一个 promise 和resolve() (如您的第一个resolveAfter2Seconds )中,要么使用类似辅助 sleep 方法的方法:

 const sleep = n => new Promise(res => setTimeout(res, n)); async function resolveAfter2Seconds() { await sleep(2000); return "resolved"; } async function asyncCall() { console.log('calling'); const result = await resolveAfter2Seconds(); console.log(result); // expected output: "resolved" } asyncCall();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM