猿问

A、B两个操作在需要等一个异步操作完成后操作

A、B两个操作在需要等一个网络请求完成后操作,但是可能是A,也可能是B,还可能是AB或者BA,AB两个操作在不同的js文件中
对于这种情况大家一般怎么处理的呢?谢谢了!
ps:请求在微信小程序中,无法添加async: false属性


先谢谢大家的回答了,我之前也是想过promise的。但是这个网络请求是在app()里面的。

这里怎么使用promise就觉得有点没有头绪。

杨__羊羊
浏览 699回答 5
5回答

心有法竹

简单粗暴:监听一段时间(自定义,如20秒)//两个请求是否完成的状态,在每个请求里面回填这个状态,改成1var wait = 20, result = { ajax1: 0, ajax2: 0 };var siFlag = setInterval(function () {&nbsp; &nbsp; wait--;&nbsp; &nbsp; if (wait < 1) {&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(siFlag);&nbsp; &nbsp; }&nbsp; &nbsp; var isComplete = true;&nbsp; &nbsp; for (var i in result) {&nbsp; &nbsp; &nbsp; &nbsp; if (!result[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isComplete = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(wait);&nbsp; &nbsp; //都完成时&nbsp; &nbsp; if (isComplete) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("isComplete TODO");&nbsp; &nbsp; }}, 1000);//直接拷贝到控制台执行,能看效果,运行的过程中,尝试改变result对象两个属性的值

翻阅古今

let in=falseA(){C()}B(){C()}C(){if(in){&nbsp; &nbsp; return}in = true}其实我也是瞎写的

动漫人物

Promise.all 应该可以

喵喵时光机

用Promise并行吧,几个异步事件一起执行,一起拿到结果,最后完成那个完成了,才获取所有的异步返回值(集合)var a = function(){&nbsp; &nbsp; return new Promise(function(resolve, reject){&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('a');&nbsp; &nbsp; &nbsp; &nbsp; },2000);&nbsp; &nbsp; })}var b = function(){&nbsp; &nbsp; return new Promise(function(resolve, reject){&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('b');&nbsp; &nbsp; &nbsp; &nbsp; },1000);&nbsp; &nbsp; })}var c = function(){&nbsp; &nbsp; return new Promise(function(resolve, reject){&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve('c');&nbsp; &nbsp; &nbsp; &nbsp; },3000);&nbsp; &nbsp; })}Promise.all([a(),b(),c()]).then(function(val){&nbsp; &nbsp; &nbsp; &nbsp; console.log(val);})你如果是只要有请求完成就行,那么用竞速,最先完成的完成了就执行,返回最先完成的那个异步的值Promise.race([a(),b(),c()]).then(function(val){&nbsp; &nbsp; &nbsp; &nbsp; console.log(val);})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答