var cordinats = function () { return new Promise(function(resolve, reject){ if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var long = position.coords.longitude, lat = position.coords.latitude; var myLocation = { long: long, lat: lat }; console.log('Оп1'); resolve(myLocation); console.log(myLocation); }) } var errObj = { 0: "Unkonown Error", 1: "Permission denied by User", 2: "Position is not available", 3: "Request Timed Out" } console.log('Оп2'); reject(`${err.code} ${errObj[err.code] }`); }); } cordinats().then(function(location) { var loc = location; console.log(loc); changeHtmlInfo(); }, function(error) { }); I open the code through Chrome. At first, Op2 appears in the console. Then, when confirming data on geolocation readout - Op1. The last console.log (loc) is not executed at all. Question:
- why such a sequence of code execution
- Why not
cordinats().then
function(error) { console.log("UPS... Reject") }will be executed much earlier. It looks likegetCurrentPositionasynchronous and while it reaches it, the cancellation will occur earlier. - Alex Krassthenmethod there are two parameters: the first is responsible for the successful resolution of the promise (resolve), the second is responsible for the unsuccessful (reject). Since you outputОп2, you callreject(...);and you smoothly transfer to the function that you passed by the second parameter tothen. Since it is empty, you don’t see anything - Grundyrejectfirst, even if you entered anif, but since insideifoperation is asynchronous, its callback will be executed after the completion of the main function - Grundy