简体   繁体   English

Javascript异步/等待for循环

[英]Javascript async/await in for loop

I have a problem 我有个问题

async function checkOk(listNotOkLocation) {
    // console.log(listNotOkLocation)
    var lenNotOk = listNotOkLocation.length
    if (lenNotOk == 0) return 'green'
    var latMarker = markerLocation.getPosition().lat()
    var lngMarker = markerLocation.getPosition().lng()
    var origin = latMarker.toString() + ", " + lngMarker.toString()

    for (var i = 0; i < lenNotOk; i++) {
        var lat = listNotOkLocation[i].lat
        var lng = listNotOkLocation[i].lng
        var destination = lat.toString() + ", " + lng.toString()
        calcRoute(origin,destination, function (err, dist) {
            console.log(1)
            if (!err) {        
                if (dist <= minDistance) 
                    return 'red'
            }
        });
    }
    console.log(2)
    return 'green'
}

Function calcRoute in for loop takes time, so function checkOk always returns 'green'. for循环中的calcRoute函数需要时间,因此checkOk函数始终返回“绿色”。 Can someone help me to solve this problem? 有人可以帮我解决这个问题吗?

wrap your calcRoute into something that returns a promise 将您的calcRoute包装成可以返回承诺的内容

function calcRouteP(origin, destination) {
  return new Promise((resolve, reject) => {
    calcRoute(origin, destination, function (err, dist) {
      if (err) {
        reject(err);
      } else {
        resolve(dist);
      }
    });
  });
}

Then use it in your async function 然后在异步功能中使用它

async function checkOk(listNotOkLocation) {
    // console.log(listNotOkLocation)
    var lenNotOk = listNotOkLocation.length
    if (lenNotOk == 0) return 'green'
    var latMarker = markerLocation.getPosition().lat()
    var lngMarker = markerLocation.getPosition().lng()
    var origin = latMarker.toString() + ", " + lngMarker.toString()

    for (var i = 0; i < lenNotOk; i++) {
        var lat = listNotOkLocation[i].lat
        var lng = listNotOkLocation[i].lng
        var destination = lat.toString() + ", " + lng.toString()
        var dist = await calcRouteP(origin,destination);
        if (dist <= minDistance) {
          return 'red'
        }
    }
    console.log(2)
    return 'green'
}

note that for functions who's last argument is a callback that is passed err, result like your calcRoute function there are often libraries to do the wrapping for you. 请注意,对于最后一个参数是传递了err, result的回调的函数err, result类似于calcRoute函数,通常会有库为您包装。 In node.js instead of wrapping calcRoute yourself you can do this 在node.js中,而不是自己包装calcRoute您可以执行此操作

const util = require('util');
const calcRouteP = util.promisifiy(calcRoute);

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

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