0

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'. Can someone help me to solve this problem?

1
  • 1
    Putting async in front of a function allows you to use await in the function, but you can only await things that return promises. calcRoute takes a callback so it's not going to work unless you do something else or wrap it in a promise. Commented Jul 17, 2019 at 3:13

1 Answer 1

3

wrap your calcRoute into something that returns a promise

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. In node.js instead of wrapping calcRoute yourself you can do this

const util = require('util');
const calcRouteP = util.promisifiy(calcRoute);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.