引入两个script标签,如何等第一个script里的异步执行完成后才加载第二个script

希望的执行顺序
console.log('1111 - index1');
console.log('2222 - index2');

文件1

function timeout(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

async function asyncPrint(value, ms) {
    await timeout(ms);
    console.log('1111 - index1');
}

asyncPrint('hello world', 1000);

文件2

(function () {
    console.log('2222-index2')
})()
阅读 2.2k
2 个回答

直接写两个script行不通
1、第一个script里的异步完成时,再去append第二个script,让他加载
2、第一个script里的异步完成时,使用import()加载第二个script的资源

把打印写到文件2

(async function (){ 
await asyncPrint("hw",1000)
console.log('2222-index2')
 })()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题