简体   繁体   English

javascript中promise的执行顺序

[英]Order of execution in promises in javascript

I have a sample program to understand how promises and async/ await works.我有一个示例程序来了解promisesasync/ await是如何工作的。 But am a little bit confused about the execution order of promises.但是我对 Promise 的执行顺序有点困惑。 Can anybody explain how this works?任何人都可以解释这是如何工作的吗?

CASE1情况1

//Promise 1
let promiseTest = new Promise((resolve, reject) => {
  var k = 0;
  for(i=0; i< 1000; i++ ){
    k += i;
  }
  resolve(k);
  console.log("Inside promise1")
});

promiseTest.then((res)=> {
    console.log('Promise1 result : '+ res);
}).then(() => {
    promiseTest2.then((res) => {
        console.log(res)
    });
}).then(finish)
.catch((err) => {
 console.log(err)
});

//Promise 2
let promiseTest2 = new Promise ((resolve, reject) => {
    console.log("Inside promise2")
});

function finish(){
    console.log("finished promise");
}

For this am geting the result as为此,我得到的结果为

RESULT结果

Inside promise1
Inside promise2
Promise1 result : 499500
finished promise

CASE2案例2

I have another example doing the same with async/ await.我还有另一个例子,用 async/await 做同样的事情。 But in this order of execution is correct.但是按照这个执行顺序是正确的。

//Async await test
async function AsyncTest(){
    console.log("Inside async1")
    var k = 0;
    for(i=0; i< 1000; i++ ){
      k += i;
    }
  console.log('async1 result : '+ k);
  const result =  await AsyncTest2();
  console.log(result)
  console.log("finished async");
}

async function AsyncTest2(){
   return "Inside async2";
}

AsyncTest();

RESULT结果

Inside async1
async1 result : 499500
Inside async2
finished async

Thanks.谢谢。

If you call .then(cb) on a Promise, a new Promise gets created and returned by it, that will resolve to whatever the callbback returns .如果您在 Promise 上调用.then(cb) ,则会创建一个新的 Promise 并由它返回,它将解析为回调返回的任何内容。 If that is a Promise itself, that Promise will be awaited before the chain continues.如果那是 Promise 本身,则在链继续之前将等待该 Promise。 In your case you did:在你的情况下,你做了:

promiseTest.then((res)=> {
 console.log('Promise1 result : '+ res);
 return undefined; // implicit return
}).then(() => {
 /* doesnt matter what you do here */
 return undefined;
}).then(finish)

Wether you attach another .then to another promise does not matter to this chain of promises.您是否将另一个.then附加到另一个承诺与此承诺链无关。

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

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