如何用promise实现这个方法

use*_*050 1 javascript asp.net-mvc promise

我如何使用promise等待异步地理编码方法返回结果然后返回true或false?

function LocationValidator(value, element, paras) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
    if (status == google.maps.GeocoderStatus.OK) {
        return true;
    } else {
        return false;
    }
});
}
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 6

在您现在居住的浏览器世界中,您如何创建自己的承诺,遗憾的是取决于您使用的承诺库.以下几种方法可以创建一个geocode(address)通过promise返回结果的函数:

// jQuery promises
function geocode(address) {
    var geocoder = new google.maps.Geocoder();

    var def = $.Deferred();
    geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
        if (status == google.maps.GeocoderStatus.OK) {
            def.resolve(results);
        } else {
            def.reject(status);
        }
    });
    return def.promise();
}

// ES6 style (supported by many polyfills, promise libraries and some browsers natively)
// my favorite library is Bluebird which this would work with
function geocode(address) {
    var geocoder = new google.maps.Geocoder();

    return new Promise(function(resolve, reject) {
        geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
            if (status == google.maps.GeocoderStatus.OK) {
                resolve(results);
            } else {
                reject(status);
            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

两者都可以像这样使用,既简单又简单:

geocode(address).then(function(result) {
    // code here that can use the result
}, function(errStatus) {
    // code here to handle an error
});
Run Code Online (Sandbox Code Playgroud)

注意:您不能进行这样的异步操作并使其进入同步操作.你不能在Javascript中这样做.因此,您必须学习如何使用异步操作进行编程,并且承诺是一种方便的方法.


其他参考:

在承诺中包装Google地图geocoder.geocode

Google API JavaScript客户端库中的承诺

如何将现有的回调API转换为承诺?