js控制异步输出顺序

class Test {
  constructor() {
    const nums = [1, 2, 3];
    (async() => {
      for(let i of nums) {
        let x = await this.print(i);
        console.log(x);
      }
    })();
  }

  print(x) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(x);
      }, 1000);
    })
  }
}

const test = new Test();

(async() => {
  let x4 = await test.print(4);
  console.log(x4);
  let x5 = await test.print(5);
  console.log(x5);
})();

怎样才能做到顺序输出 1 2 3 4 5 ?

阅读 2.7k
3 个回答

Test类增加一个cprm属性,用来接收构造函数里面的异步调用,值是Promise类型。然后在调用输出4之前await这个cprm属性,就可以等到构造函数的123都输出完成后再输出4。

class Test {
  constructor() {
    const nums = [1, 2, 3];
    this.cprm=(async() => {
      for(let i of nums) {
        let x = await this.print(i);
        console.log(x);
      }
    })();
  }

  print(x) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(x);
      }, 1000);
    })
  }
}

const test = new Test();


(async() => {
  await test.cprm;
  let x4 = await test.print(4);
  console.log(x4);
  let x5 = await test.print(5);
  console.log(x5);
})();

    class Test {
        constructor() {
            const nums = [1, 2, 3];
            this.init = Promise.all(nums.map(async n=>console.log(await this.print(n, true))));
        }

        print(x, isInit =false) {
            return (isInit ? Promise.resolve() : this.init).then(()=> new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(x);
                }
                , 1000);
            }
            ));
        }
    }

    const test = new Test();

    (async()=>{
        let x4 = await test.print(4);
        console.log(x4);
        let x5 = await test.print(5);
        console.log(x5);
    }
    )();
}

我来投机取巧,~( ̄▽ ̄)~*

class Test {
  constructor() {
    const nums = [1, 2, 3];
    (async() => {
      for(let i of nums) {
        let x = await this.print(i);
        console.log(x);
      }
    })();
  }

  print(x) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(x);
      }, 1000);
    })
  }
}

const test = new Test();
setTimeout(async() => {
  let x4 = await test.print(4);
  console.log(x4);
  let x5 = await test.print(5);
  console.log(x5);
}, 3000)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题