function awaitDome(){
return new Promise((r) = > {
setTimeout(function(){
r(1)
console.log(1)},2000)})}async function asyncDome(){
console.log('await'.await awaitDome())
console.log(2)}Copy the code
This is easy if there is only one asynchronous operation
function awaitDome(){
return new Promise((r) = > {
setTimeout(function(){
r(1)
console.log(1)},2000)
})
}
awaitDome().then(r= > console.log(r))
Copy the code
If it’s a loop or multiple, if you’re dealing with a list of arrays in order now and you’re not doing it synchronously, you might not want to do it if you’re not doing it synchronously. For example, if you’re doing a waterfall of your applet, you need to add elements one by one to get the height of the list
/ / the iterator
var a = [1.2.3.4.5.6.7]
function createIterator(items) {
var i = 0;
return {
next: function() {
var done = (i >= items.length);
varvalue = ! done ? items[i++] :undefined;
return {
done: done,
value: value }; }}; }var iteratorDome = createIterator(a)
function awaitDome(i){
return new Promise((r) = > {
setTimeout(function(){
r(i)
},2000)})}function next(){
var iterator = iteratorDome.next()
console.log(iterator)
awaitDome(iterator.value).then(r= > {
console.log(r)
if(! iterator.done){ next() } }) } next()// Execute the following result
Copy the code
If you just loop through it
var gg = new Date(a)var a = [1.2.3.4.5.6.7]
function awaitDome(i){
return new Promise((r) = > {
setTimeout(function(){
r(i)
console.log(new Date() - gg)
},i * 500)
})
}
a.forEach((e) = > {
awaitDome(e).then(r= > {
console.log(r)
})
})
Copy the code
The figure above shows the basic 500ms execution but actually wants the result
/ / the iterator
var gg = new Date(a)var a = [1.2.3.4.5.6.7]
function createIterator(items) {
var i = 0;
return {
next: function() {
var done = (i >= items.length);
varvalue = ! done ? items[i++] :undefined;
return {
done: done,
value: value }; }}; }var iteratorDome = createIterator(a)
function awaitDome(i){
return new Promise((r) = > {
setTimeout(function(){
r(i)
console.log(new Date() - gg)
},i * 500)})}function next(){
var iterator = iteratorDome.next()
console.log(iterator)
awaitDome(iterator.value).then(r= > {
console.log(r)
if(! iterator.done){ next() } }) } next()// Execute the following result
Copy the code
Because normally we call the interface and the order in which the data is returned is asynchronous and when we want to return in order we have to synchronizeIn accordance with the
Called sequentially